What is Terraform State: Explanation and Usage
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 {
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"
}
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.