Module 6, Terraform Workflow in Depth
The Core Workflow
Write → Init → Fmt → Validate → Plan → Apply → Destroy
terraform init
Downloads providers and modules. Must run after:
- First time in a new directory
- Adding a new provider or module
- Changing backend configuration
terraform init # standard
terraform init -upgrade # upgrade providers to latest allowed versions
terraform init -reconfigure # switch to a different backend
terraform plan
The most important command. Shows exactly what Terraform will do without doing it.
terraform plan
terraform plan -out=tfplan # save for CI/CD apply
terraform plan -destroy # preview full destroy
terraform plan -target=aws_s3_bucket.main # target one resource
terraform plan -var="environment=staging" # override a variable
Reading Plan Output
+ create (green) , new resource
- destroy (red) , resource deleted
~ update (yellow), modified in-place, no downtime
-/+ replace (red+green), DESTROY then RECREATE, potential downtime!
<= read , data source will be queried
danger
Always search your plan output for -/+ before typing yes. A replacement means the resource is destroyed and recreated, this causes downtime and potential data loss.
terraform apply
terraform apply # interactive, prompts for confirmation
terraform apply -auto-approve # skip prompt (CI/CD only)
terraform apply tfplan # apply a saved plan exactly as reviewed
terraform apply -target=aws_s3_bucket.main
terraform destroy
terraform destroy # destroy everything
terraform destroy -target=aws_s3_bucket.main # destroy one resource
terraform destroy -auto-approve # no prompt (CI/CD teardown)
terraform fmt and validate
terraform fmt # auto-format to canonical style
terraform fmt -recursive # format all subdirectories
terraform fmt -check # check without changing (use in CI)
terraform validate # check syntax and internal consistency (no AWS calls)
The CI/CD Workflow
# On pull request:
- terraform fmt -check # fail if code is not formatted
- terraform validate # fail if syntax is invalid
- terraform plan -out=tfplan # post the plan as a PR comment
# On merge to main:
- terraform apply tfplan # apply the EXACT plan that was reviewed
tip
Using terraform apply tfplan (not bare terraform apply) in CI ensures you apply exactly what was reviewed. A bare apply re-plans and could create different results.
Knowledge Check
- What does
terraform init -upgradedo? - What is the difference between
terraform plan -out=tfplanandterraform apply? - What does a
-/+symbol mean in plan output? - Why is
-auto-approvedangerous in production but acceptable in CI/CD? - What does
terraform fmt -checkdo in a pipeline? - You changed an RDS
identifier. What does the plan show?
Exam Mapping
- HashiCorp Associate Obj 6: Navigate Terraform workflow (25-35% of exam, most tested!)
- AWS DevOps Pro Domain 1: Deployment strategies