Terraform

Terraform fmt Command – How to Format Terraform Code

Formatting Terraform Code With the Terraform fmt Command

In this post, we will look at the terraform fmt command, first explaining what it does and when to run it, looking at the operation it performs, and showing some useful examples using the available options.

What is Terraform fmt?

The terraform fmt command is used to format your configuration files into a canonical format and style. This command applies a subset of the Terraform language style conventions, along with other minor adjustments for readability.

Using the Terraform fmt Command with Examples

Usage: terraform fmt [options] [TARGET]

terraform fmt example main tf
  • Terraform lists the main.tf file after my terraform fmtcommand to show that it was changed. To stop this from being listed, the -list=false option can be used. Alternatively, the -write=false option will list the files to be changed but not actually write the changes.
  • The extra spaces in the backend block and in the ad_group module call are not removed. That has to be done manually if required.
terraform fmt main tf error
choco install diffutils

Once installed, restart your terminal, and the diff will be successfully generated:

Key Points

I hope with this blog post, you learned how to format your Terraform code with the Terraform fmt command.

If you’re interested in finding out how to use Spacelift to manage and automate your Terraform deployments check out our Terraform documentation and sign up for a free trial.

Cheers!

Manage Terraform Better with Spacelift

Build more complex workflows based on Terraform using policy as code, programmatic configuration, context sharing, drift detection, resource visualization, and many more.

Start free trial