Terraform by Example: Backends
Backends define where state is stored. This sample code configures an S3 remote backend with DynamoDB state locking for secure collaboration.
Code
terraform {
backend "s3" {
bucket = "my-corp-terraform-state"
key = "prod/app-server/terraform.tfstate"
region = "us-east-1"
# Enable state locking via DynamoDB
dynamodb_table = "terraform-state-locks"
encrypt = true
}
}
# No resources needed for this example,
# but this config tells Terraform where to store the state file.Explanation
A "backend" defines where Terraform stores its state data files. While the default "local" backend is fine for individual learning, it is critical to use a remote backend (like AWS S3, Azure Blob Storage, or Terraform Cloud) for any team or production environment. Remote backends enable collaboration by sharing the state file, prevent data loss, and support state locking.
The S3 backend is a popular choice for AWS users. It stores the state as a JSON file in an S3 bucket. Crucially, it supports state locking via a DynamoDB table. This locking mechanism prevents multiple team members or CI/CD jobs from running terraform apply simultaneously, which could otherwise corrupt the state file and damage your infrastructure.
Security is a major concern with state files, as they often contain sensitive data in plain text. Therefore, it is best practice to enable encryption at rest (using encrypt = true) and strictly control access to the storage bucket. When migrating from a local to a remote backend, you must run terraform init to copy your existing state to the new location.
Code Breakdown
backend "s3" defines the storage location.bucket specifies the S3 bucket name for state storage.key is the path to the state file within the bucket.region is the AWS region where the bucket is located.dynamodb_table enables locking, preventing concurrent modifications.encrypt = true ensures the state file is encrypted at rest in S3.
