formatting Terraform code

2 min read

One of the nicest functions terraform has is terraform fmt: Just as go fmt would do with Go code, it will rewrite Terraform configuration files (.tf and .tfvars files) to a canonical format and style. This will improve it's readability, helping making the code more consistent.

It's usage it cannot be more straightforward, you just need to run it on the directory that contains the terraform code. It will scan for .tf and .tfvars file to be restyled:

::: text
$ terraform fmt -help
Usage: terraform fmt [options] [DIR]

  Rewrites all Terraform configuration files to a canonical format. Both
  configuration files (.tf) and variables files (.tfvars) are updated.
  JSON files (.tf.json or .tfvars.json) are not modified.

  If DIR is not specified then the current working directory will be used.
  If DIR is "-" then content will be read from STDIN. The given content must
  be in the Terraform language native syntax; JSON is not supported.

(...)

As output you will get the list of files that have been modified, for example:

$ terraform fmt
azure-main.tf

These are the changes terraform fmt made using the 0.14 version on this demo code for Azure

The canonical format may change between Terraform versions, for after upgrading is recommended to also update the format.


Posted on 06/05/2021

Categories