Managing Terraform state – Infrastructure as Code (IaC) with Terraform

Terraform uses a state file to track what it has deployed and what resources it is managing. The state file is essential as it records all the infrastructure Terraform maintains. If you lose it, Terraform will lose track of what it has done so far and start treating resources as new and needing to be created again. Therefore, you should protect your state as code.

Terraform stores state in backends. By default, Terraform stores the state file as terraform.tfstate within the workspace directory, which is called the local backend. However, that is not the best way of managing the state. There are a couple of reasons why you should not store state in a local system:

  • Multiple admins cannot work on the same infrastructure if the state file is stored within someone’s local directory
  • Local workstations are not backed up; therefore, the risk of losing the state file is high even if you have a single admin doing the job

You might argue that we can resolve these problems by checking the state file into source control with the .tf files. Don’t do that! State files are plaintext, and if your infrastructure configuration contains sensitive information such as passwords, anyone can see it. Therefore, you need to store a state file securely. Also, storing state files in source control does not provide state locking, resulting in conflicts if multiple people are simultaneously modifying the state file.

Tip

Never store state files in source control. Use a .gitignore file entry to bypass the terraform.

tfstate file.

The best place to store your Terraform state is on remote cloud storage. Terraform provides a remote backend to store state remotely. There are multiple types of remote backends you can use. When writing

this book, Azure RM, Consul, cos, gcs, http, Kubernetes, oss, pg, S3, and Remote were available backends. Remote is an enhanced backend type that allows running Terraform plan and apply

within the backend, and only Terraform Cloud and Enterprise support it.

Tip

While choosing the state storage solution, you should prefer storage with state locking. That will allow multiple people to manipulate the resources without stepping on each other’s shoes and causing conflict, as once a state file is locked, others cannot acquire it until the lock is released.

As we’re using Azure, we can use Azure Storage to store our state. The advantages are three-fold:

  • Your state file is centralized. You can have multiple admins working together and managing the same infrastructure.
  • The store is encrypted at rest.
  • You get automatic backup, redundancy, and high availability.

To access the resources for this section, cd into the following:

$ cd ~/modern-devops/ch8/terraform-backend/

Let’s now use the azurerm backend and use Azure Storage to persist our Terraform state.

Leave a Reply

Your email address will not be published. Required fields are marked *