This post is the fourth in the series which focuses on point 4 in the list, 'Use a consistent format and style'.

  1. Use a consistent file structure across your projects.
  2. Use modules wherever possible.
  3. Use a consistent naming convention.
  4. Use a consistent format and style.
  5. Hold your state file remotely, not on your local machine.
  6. Avoid hardcoding variables.
  7. Fewer resources in a project are easier and faster to work with.
  8. Limit resources in the project to reduce the blast radius.
  9. Test your code.
None

Use a consistent format, style & code structure

Format, style, and structure are slightly subjective, however, to ensure consistency you should agree on some standards with your team.

I recommend at least checking the following before checking in any code:

Use Terraform fmt

Using terraform fmt will rewrite your configuration files in a standard format and style.

Check your code syntax

Using terraform validate to check your code syntax will make certain the code is valid.

Place count, tags, depends_on and lifecycle blocks of code in consistent locations within resources

If used, the Count argument should always come as the first line inside the resource block and be separated by a new line.

The tags, depends_on and lifecycle blocks if applicable should always be listed as the last arguments, always in the same order. These should be separated by a new line.

e.g.

resource "azurerm_virtual_machine" "azurerm_desktop" {
   count  = "2"
   name = var.vm_name
   # other arguments omitted
   tags = {
     Env = "Prod"
   }
   depends_on = ["azurerm_network_interface.this"]
   lifecycle {
     create_before_destroy = true
   }
}

To make sure your code follows these patterns, you could write a policy(-as-code) using Terraform Sentinel if you have the paid-for Terraform Cloud or Enterprise versions.

There are a host of other testing tools out there you could integrate with your CI pipelines, including terraform-compliance, Terratest, checkov, tfsec, or cloudrail that could be used to make sure a tags block is included. More on that later in the series!

Short and sweet!

Want more Terraform content? Check out my other articles on Terraform here!

Cheers! 🍻