Formatting
How to use the built-in tools for formatting.
Format
Terraform has a way of formatting code. It is solely a question about style, however, consistensy in this will produce better looking code, and thus, code that is much more readable.
To format, use:
terraform fmt
However, this only formats the current directory, so to format everything use:
terraform fmt -recursive .
recursivemeans checking every folder..means start from the current folder.
Doing this, searches for all .tf and .tfvars files and rewrites files to match the styling considered canon by HCL.
Example
Before:
resource "hcloud_server" "web" {
name = "web-01"
server_type="cx22"
image = "ubuntu-24.04"
location="hel1"
labels = {
env="prod"
app = "portfolio"
}
}
After:
resource "hcloud_server" "web" {
name = "web-01"
server_type = "cx22"
image = "ubuntu-24.04"
location = "hel1"
labels = {
env = "prod"
app = "portfolio"
}
}
Using terraform fmt -check in your pipeline makes the step fail if any files are not properly formatted. This keeps the code consistent and the pull requests free of formatting changes.