Configure S3/GCS Remote State Backend
Beginner10 min
Set up a remote state backend with S3 or GCS for team collaboration, state locking, and disaster recovery.
Prerequisites
- -Terraform installed
- -AWS or GCP credentials configured
Steps
1
Create the S3 bucket for state storage
Create a versioned, encrypted S3 bucket to store Terraform state files.
$ aws s3api create-bucket --bucket my-tf-state-bucket --region us-east-1
aws s3api put-bucket-versioning --bucket my-tf-state-bucket --versioning-configuration Status=Enabled
aws s3api put-bucket-encryption --bucket my-tf-state-bucket --server-side-encryption-configuration '{"Rules":[{"ApplyServerSideEncryptionByDefault":{"SSEAlgorithm":"AES256"}}]}'
Enable versioning to recover from accidental state corruption or deletion.
2
Create a DynamoDB table for state locking
Create a DynamoDB table to enable state locking, preventing concurrent operations.
$ aws dynamodb create-table --table-name tf-state-lock --attribute-definitions AttributeName=LockID,AttributeType=S --key-schema AttributeName=LockID,KeyType=HASH --billing-mode PAY_PER_REQUEST
3
Configure the backend in Terraform
Add the S3 backend configuration to your Terraform code.
$ cat <<'EOF' > backend.tf
terraform {
backend "s3" {
bucket = "my-tf-state-bucket"
key = "global/terraform.tfstate"
region = "us-east-1"
dynamodb_table = "tf-state-lock"
encrypt = true
}
}
EOF
4
Initialize the backend
Run terraform init to configure the backend and migrate any existing local state.
$ terraform init
If you have existing local state, Terraform will ask if you want to migrate it. Answer 'yes' to preserve your resources.
5
Verify the backend is working
Confirm that state is being stored remotely and locking is functional.
$ terraform state list && aws s3 ls s3://my-tf-state-bucket/global/
Full Script
FAQ
Discussion
Loading comments...