LinuxCommandLibrary

terraform-fmt

Format Terraform configuration files

TLDR

Format the configuration in the current directory

$ terraform fmt
copy

Format the configuration in the current directory and subdirectories
$ terraform fmt -recursive
copy

Display diffs of formatting changes
$ terraform fmt -diff
copy

Do not list files that were formatted to stdout
$ terraform fmt -list=false
copy

SYNOPSIS

terraform fmt [options] [path]

PARAMETERS

-recursive
    Recursively apply formatting to all Terraform configuration files in the specified directory and its subdirectories.

-write=true|false
    Indicates whether to write the formatted files back to disk (true) or only display the changes (false). Default is true.

-diff
    Display a diff of the changes that would be made by formatting the files.

-list=true|false
    List files whose formatting differs from the canonical format.

path
    The path to a Terraform configuration file or directory to format. If no path is specified, the current directory is used.

DESCRIPTION

terraform fmt is a command-line tool included with Terraform that automatically formats Terraform configuration files to adhere to a canonical style. It helps ensure consistency and readability across projects, making it easier for teams to collaborate.

It applies a standard set of formatting rules, including indentation, spacing, and line breaks, ensuring that all Terraform code within a project follows a consistent style guide. The command modifies files in-place by default or can output the formatted result to stdout.

By automating the formatting process, terraform fmt reduces the manual effort required to maintain consistent code style, preventing stylistic debates, minimizing errors and making code easier to maintain and review.

CAVEATS

terraform fmt modifies files in-place by default. Make sure to have a backup or use version control before running this command. It's also important that all files in a single directory use the same version of Terraform language features to ensure proper parsing and formatting.

EXIT CODES

The command exits with 0 if all files are formatted correctly. A non-zero exit code indicates an error during formatting or that files were not formatted correctly when using the -list flag.

HISTORY

The terraform fmt command was introduced as part of the core Terraform functionality to address the need for consistent code style. As Terraform gained popularity and adoption within teams, the lack of a standardized formatting tool led to inconsistencies and challenges in code maintenance. terraform fmt aimed to solve this problem by providing an automated and reliable way to enforce a canonical style, promoting code readability and collaboration.

SEE ALSO

terraform(1), terraform-validate(1)

Copied to clipboard