When starting out with Terraform it’s hard to know what is considered ‘best practice’ in a number of areas.

This post is the fifth in the series which focuses on point 5 in the list, ‘Hold your state file remotely, not on your local machine’.

  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

What is the Terraform ‘state’ file?

Terraform maintains a state file that maps the current status of your infrastructure with your configuration files.

The state file is commonly stored either on a local machine, in a remote storage location (like a storage account in Azure, or S3 bucket in AWS), or in Terraform cloud.

By default, it is stored on the local machine and is named “terraform.tfstate”.

The state file can include sensitive values in plain text, and so it is recommended it is always stored on media that is encrypted-at-rest.

Why not to keep the state file on your local machine

The best practice is never to store the state file on your local machine.

As mentioned previously, the state file may include sensitive values in plain text, representing a security risk, anyone with access to your machine or this file can potentially view it.

Storing it in a shared area such as an Azure storage account enables other developers to access the state file to collaborate on the Terraform project. This would not be possible when stored on a local machine. As multiple users access the same state file, the state file should be locked when it is in use. This is easy to setup (supported natively in Azure storage, or by using a dynamoDB in AWS for example).

State file in an Azure Storage account

The exact config will depend on how you are authenticating to Azure. Locking is a native capability of Azure Storage so there is no need to do anything extra to enable it.

#devops #infrastructure-as-code #terraform

Terraform Best Practices — Hold your state file remotely, not on your local machine
1.20 GEEK