Going to AWS Summit London? 🇬🇧🇬🇧

Meet us there →


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.

Note: New versions of Terraform will be placed under the BUSL license, but everything created before version 1.5.x stays open-source. OpenTofu is an open-source version of Terraform that will expand on Terraform’s existing concepts and offerings. It is a viable alternative to HashiCorp’s Terraform, being forked from Terraform version 1.5.6. OpenTofu retained all the features and functionalities that had made Terraform popular among developers while also introducing improvements and enhancements. OpenTofu works with your existing Terraform state file, so you won’t have any issues when you are migrating to it.

Using the Terraform fmt Command with Examples

Usage: terraform fmt [options] [TARGET]

terraform fmt example main tf
terraform fmt file example
  • 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
terraform fmt install choco

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

terraform fmt diff

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.


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
Terraform CLI Commands Cheatsheet

Initialize/ plan/ apply your IaC, manage modules, state, and more.

Share your data and download the cheatsheet