Terraform-Associate-004 practice question 35 of 35

Which command should you run to check if all code in a Terraform configuration that references multiple modules is properly formatted without making changes?

Full set: 360 questions
Answer options
A: terraform fmt -write-false
B: terraform fmt -list -recursive
C: terraform fmt -check -recursive Correct answer
D: terraform fmt -check
Correct Answer:
C. terraform fmt -check -recursive
Explanation

The terraform fmt command is used to rewrite Terraform configuration files to a canonical format and style. To satisfy the requirement of checking formatting without applying changes, the -check flag is used. This flag makes the command exit with a non-zero status code if any files are not correctly formatted, making it ideal for CI/CD validation pipelines. Since the configuration references multiple modules, which are typically located in subdirectories, the -recursive flag is also required to ensure the command processes files in the entire module tree, not just the current directory.

Why Incorrect

A. terraform fmt -write-false: This prevents writing changes but does not provide a clear exit code for automation to indicate if files are unformatted, unlike the dedicated -check flag.
B. terraform fmt -list -recursive: This lists the files that need formatting but does not provide the explicit pass/fail exit code that the -check flag does for validation purposes.
D. terraform fmt -check: This option correctly checks the formatting but fails to process the files within the referenced modules, as it does not operate recursively on subdirectories.

References

1. HashiCorp Terraform Documentation, fmt Command:

Section: Options

-check: "Check if the input is formatted. Exit status will be 0 if all input is formatted correctly and 1 if any input is not formatted. An error message will be printed to stderr for each file that is not formatted."

-recursive: "Also process files in subdirectories. By default, only files in the given directory are processed."

Source: HashiCorp, Terraform CLI - Command: fmt, developer.hashicorp.com/terraform/cli/commands/fmt. Accessed May 2024.

Scroll to Top