Skip to main content

Google publishes a list of Terraform best-practices

·470 words·3 mins
Terraform Google

Google recently published a list of best-practices for using Terraform. The full list is available here, but I will highlight a few of the best-practices that I like.

Follow a standard module structure
#

This is the first best-practice in the list of best-practices and it is an important one! If you work a lot with Terraform it helps if all the modules you encounter follow a certain structure. This means you can know where you find all the variables, all the outputs, etc.

Protect stateful resources
#

This should be a no-brainer once you have been burned once. Have you accidentally deleted an important database? That should not happen if you protect your stateful resources.

Pin to minor provider versions
#

Personally I have never been affected by issues related to this, but once it happens (and I guess it will) it will be annoying. When you specify the version of a provider you want to use, you should use the ~> 4.0.0 syntax, the ~> means that the major and the minor versions are pinned, while the patch number can vary. What happens if we do not do this? We could end up accidentally upgrading a provider to a higher major or minor version, and if we are unlucky the upgrade breaks our Terraform configuration

terraform {
  required_providers {
    google = {
      source  = "hashicorp/google"
      version = "~> 4.0.0"
    }
  }
}

Never commit secrets
#

This is another no-brainer, yet I have done it, and probably you too? We should be careful to temporarily add secrets to our files “just to test”. Chances are we forget that we added something in the name of a test, and all of a sudden the secret is in your git repository.

Always plan first
#

It is convenient to run terraform apply -auto-approve when developing your Terraform configuration, but for production scenarios it is a good idea to run an explicit terraform plan ahead of a terraform apply. You should also include an intelligent step in between that asks for manual approval if there are a certain number of changes (or any number of changes for that matter).

Don’t modify Terraform state manually
#

The third no-brainer in this list. However, sooner or later the time comes when you feel tempted to manually touch the Terraform state files. Don’t! There are other approaches you can use to manipulate the state, e.g. using the terraform state command.

Clean up all resources
#

Finally a guide that actually confirms that testing infrastructure code actually requires you to create real resources. There is just no way out of that. However, once you do create real resources you should remember to clean them up afterwards. Many are the dollars spent on paying cloud bills for resources that are just forgotten remnants of distant deployments.

Mattias Fjellström
Author
Mattias Fjellström
Cloud architect · Author · HashiCorp Ambassador