Terraform format

terraform fmt is a command in the Terraform infrastructure as code (IaC) tool that is used to

  • Format Terraform configuration files in HCL format to follow a standard style
  • Applies a set of standard formatting rules to the code, making it more readable and consistent
  • JSON files (.tf.json or .tfvars.json) are not modified.

When you run terraform fmt, it will read all the configuration files in the current directory and its subdirectories, then modify the files to adhere to the standard style.

What “terraform fmt” cannot do?

  1. It cannot validate the correctness of the code.
  2. It cannot automatically update the configuration file to a new version of Terraform.
  3. It cannot modify the logic or behavior of the code.
  4. It cannot format or work with files in other formats such as JSON or YAML.
  5. It cannot format provider-specific configurations or custom resources.

By default, terraform fmt, outputs the modified files to the standard output. To actually modify the files in place, you need to pass the -write flag.

Here is an example of how to run terraform fmt in the command line:

terraform fmt -write
BEFORE FORMATTING
AFTER FORMATTING

Note: Below are the questions that may appear in the “HashiCorp Certified: Terraform Associate”. The questions are collected from various sources and the answers are best to my knowledge and might differ from the actuals.

  1. To check if all code in a Terraform configuration with multiple modules is properly formatted without making changes, what command should be run?
  • A. terraform fmt -check
  • B. terraform fmt -write-false
  • C. terraform fmt -recursive
  • D. terraform fmt -check -recursive
F:\Terraform\Zero phase\vpc_ws1>terraform fmt -check -recursive -diff
vpc_team.tf
--- old/vpc_team.tf
+++ new/vpc_team.tf
@@ -1,11 +1,11 @@
 locals {

-  tagname =           "sar-new"
+  tagname = "sar-new"
 }
 resource "aws_vpc" "team-vpc" {
   cidr_block = lookup(var.cidrblk, terraform.workspace)
   tags = {
-    "owner" =        local.tagname
+    "owner" = local.tagname
   }
 }
  1. How can you format Terraform HCL (HashiCorp Configuration Language) code according to the standard Terraform style convention?
  • A. Run the terraform fmt command during the code linting phase of your CI/CD process
  • B. Designate one person in each team to review and format everyone’s code
  • C. Manually apply two spaces indentation and align equal sign “=” characters in every Terraform file (*.tf)
  • D. Write a shell script to transform Terraform files using tools such as AWK, Python
error: Content is protected !!