The everyday loop
terraform init # download providers, set up the backendterraform fmt -recursive # format the filesterraform validate # check the configurationterraform plan -out=tfplan # what would change, savedterraform apply tfplan # apply exactly that planterraform apply -auto-approve # plan and apply, no question (CI)terraform destroytofu takes the same commands in OpenTofu.
init options
terraform init -upgrade # newer provider versions within the constraintsterraform init -reconfigure # backend changed: start freshterraform init -migrate-state # backend changed: copy the state overterraform providers lock -platform=linux_amd64 -platform=darwin_arm64Commit .terraform.lock.hcl, not the .terraform/ folder.
Targeted changes
terraform plan -target=aws_instance.web # only this (exceptional use)terraform apply -replace=aws_instance.web # recreate itterraform plan -refresh-only # see drift, change nothingterraform plan -var 'env=prod' -var-file=prod.tfvarsState
terraform state listterraform state show aws_instance.webterraform state mv aws_instance.web aws_instance.appterraform state rm aws_instance.old # forget it, don't destroy itterraform force-unlock LOCK_ID # only if no run is still activeImport and move, in code
import { to = aws_s3_bucket.logs id = "acme-logs"}
moved { from = aws_instance.web to = aws_instance.app}terraform plan -generate-config-out=generated.tf # write resource blocks for importsOutputs, workspaces, console
terraform outputterraform output -jsonterraform output -raw db_endpointterraform workspace listterraform workspace new stagingterraform workspace select stagingterraform console # try expressions: > upper("x")Debugging
TF_LOG=DEBUG terraform plan 2> debug.logterraform graph | dot -Tsvg > graph.svgterraform versionCommon errors
Backend initialization requiredError acquiring the state lockInconsistent dependency lock fileA resource with the ID … already existssubscription is not registered to use namespace