Video Thumbnail for Lesson
3.2: Terraform State Management

Terraform State Management

We will cover the concept of the Terraform state file, its importance, and the different ways to store and manage it.

We will discuss the advantages and drawbacks of local and remote backends and explain how to use them effectively for better collaboration and security.

Understanding the State File:

  • The state file is a JSON file containing information about resources and data objects deployed using Terraform
  • It includes metadata and other essential information about each resource
  • The state file may contain sensitive information, so it must be protected and encrypted

The following is an example of a .tfstate file for a terraform config managing an s3 bucket:

{
  "version": 4,
  "terraform_version": "1.0.0",
  "serial": 1,
  "lineage": "your-lineage-here",
  "outputs": {},
  "resources": [
    {
      "mode": "managed",
      "type": "aws_s3_bucket",
      "name": "example_bucket",
      "provider": "provider.aws",
      "instances": [
        {
          "attributes": {
            "acl": "private",
            "bucket": "example-bucket",
            "force_destroy": false,
            "id": "example_bucket",
            "region": "us-east-1",
            "tags": {}
          },
          "private": "bnVsbA=="
        }
      ]
    }
  ]
}

Storing the State File:

  • Local Backend: The state file is stored within the working directory of the project
  • Remote Backend: The state file is stored in a remote object store or a managed service like Terraform Cloud

Local Backend:

Diagram of local backend
  1. Advantages:

    • Easy to set up and use
    • Stores the state file alongside your code
  2. Disadvantages:

    • Stores sensitive values in plain text
    • Not suitable for collaboration
    • Requires manual interaction for applying changes

Remote Backend:

Diagram of remote backend
  1. Advantages:

    • Encrypts sensitive data
    • Allows collaboration among multiple developers
    • Supports automation through CI/CD pipelines
  2. Disadvantages:

    • Increased complexity compared to the local backend

Remote Backend Options:

  • Terraform Cloud (managed offering)
  • Self-managed remote backends (e.g., Amazon S3, Google Cloud Storage)

Understanding Terraform state management and the differences between local and remote backends will help you choose the most suitable option for your projects, considering factors like collaboration, security, and automation.