Naren

terraform

State surgery, and the command that replaced taint.

Verified against Terraform v1.15.8. Current release is v1.16.4.

Commands

Plan to a file and apply exactly that plan, so nothing drifts between the two:

terraform plan -out=tfplan
terraform apply tfplan

Format and validate before anything else runs:

terraform fmt -recursive -check
terraform validate

Replace one resource without touching the rest:

terraform apply -replace='aws_instance.web'

Look inside state:

terraform state list
terraform state show 'module.vpc.aws_subnet.private[0]'

Rename a resource without destroying it:

terraform state mv 'aws_s3_bucket.old' 'aws_s3_bucket.new'

Stop managing something without deleting it:

terraform state rm 'aws_iam_role.legacy'

Machine readable outputs for a pipeline:

terraform output -json | jq -r '.bucket_name.value'

Try an expression against real state:

terraform console

Refresh providers and modules after changing versions:

terraform init -upgrade

Notes

terraform taint still exists and is deprecated. Use apply -replace=ADDRESS, which plans the replacement so you see it before it happens rather than marking state and finding out on the next apply.

state rm makes Terraform forget a resource. The resource keeps running and keeps costing money, so it is the start of a move, not a delete.

Quote resource addresses in zsh. Square brackets in aws_subnet.private[0] are glob characters and the shell will eat them.

plan -out writes a plan file that contains values from state, including any secrets in it. Treat it as sensitive and do not commit it.

On this page