0
0
TerraformConceptBeginner · 3 min read

What is Terraform State: Explanation and Usage

Terraform state is a file that keeps track of the resources Terraform manages. It records the current infrastructure setup so Terraform knows what to create, update, or delete when you run commands.
⚙️

How It Works

Think of Terraform state as a detailed map of your cloud resources. When you use Terraform to build or change infrastructure, it writes down what exists in this map. This helps Terraform understand what it has already created and what needs to be changed next.

Without this map, Terraform would have no memory of your infrastructure and would try to create everything from scratch every time. The state file acts like a diary that remembers your infrastructure's current condition, making updates safe and efficient.

💻

Example

This example shows a simple Terraform configuration that creates an AWS S3 bucket. After applying, Terraform saves the state file locally, tracking the bucket's details.

terraform
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.0"
    }
  }
  required_version = ">= 1.0"
}

provider "aws" {
  region = "us-east-1"
}

resource "aws_s3_bucket" "example" {
  bucket = "my-unique-terraform-state-bucket-12345"
  acl    = "private"
}
Output
Apply complete! Resources: 1 added, 0 changed, 0 destroyed. Outputs: Terraform has saved the state to the local file terraform.tfstate
🎯

When to Use

Use Terraform state whenever you manage infrastructure with Terraform. It is essential for tracking resources across multiple runs and users. In teams, storing state remotely (like in AWS S3 or Terraform Cloud) helps everyone share the same map and avoid conflicts.

Real-world use cases include managing cloud servers, databases, networks, and other resources where you want Terraform to know what exists and what needs updating without manual tracking.

Key Points

  • Terraform state records the current infrastructure managed by Terraform.
  • It enables Terraform to plan and apply changes safely.
  • State can be stored locally or remotely for team collaboration.
  • Protect your state file as it contains sensitive information.

Key Takeaways

Terraform state tracks your infrastructure's current setup for safe updates.
Always use state to let Terraform know what resources exist.
Store state remotely for team environments to avoid conflicts.
Protect the state file because it holds sensitive data.