Learn about Spacelift's latest features and capabilities 🚀🚀

Register for the Product Momentum Webinar Aug 6 →

Terraform

Using Terraform fmt Command to Format Your 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 are 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 expands on Terraform’s existing concepts and offerings. It is a viable alternative to HashiCorp’s Terraform, being forked from Terraform version 1.5.6.

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.

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

The Practitioner’s Guide to Scaling Infrastructure as Code

Transform your IaC management to scale

securely, efficiently, and productively

into the future.

ebook global banner
Share your data and download the guide