Single env
Create a backend.tf file in your root directory with,
terraform {
backend "s3" {
bucket = "terraform-state-24282348899985669082079" # bucket must exist before applying this tf config
key = "terraform.tfstate"
region = "us-east-1"
encrypt = true
}
}Then migrate the existing state,
terraform init -migrate-stateUsage,
terraform plan
terraform apply
Multiple envs
Have a backend.tf file in your root terraform directory with only the common values,
terraform {
backend "s3" {
bucket = "your-company-terraform-state"
region = "us-east-1" # Choose your region
encrypt = true
# Key will be specified in the backend config files
}
}Within each of your environment directories have a .hcl file with the env specific variable values, like,
key = "staging/terraform.tfstate"key = "prod/terraform.tfstate"Then migrate your existing state,
terraform init -backend-config="envs/staging/backend-staging.hcl" -migrate-stateThen every time you change things,
terraform init -backend-config="envs/staging/backend-staging.hcl"
terraform plan -var-file="envs/staging/staging.tfvars"
terraform apply -var-file="envs/staging/staging.tfvars"