Terraform cheatsheet
CLI essentials
| Command | Description |
|---|---|
terraform init | Initialize providers and backend |
terraform fmt -recursive | Format HCL files |
terraform validate | Validate configuration |
terraform plan | Preview changes |
terraform plan -out=plan.tfplan | Save plan for apply |
terraform apply | Apply changes |
terraform apply plan.tfplan | Apply saved plan only |
terraform destroy | Destroy managed resources |
Inspect and debug
| Command | Description |
|---|---|
terraform show | Current state or saved plan |
terraform state list | Resources in state |
terraform state show ADDR | One resource details |
terraform output | Print outputs |
terraform console | Evaluate expressions interactively |
TF_LOG=DEBUG terraform plan | Verbose provider logs |
Variables and outputs
variable "region" {
type = string
default = "us-east-1"
}
output "bucket_id" {
value = aws_s3_bucket.logs.id
}
# CLI: terraform plan -var="region=eu-west-1"
# Or: terraform plan -var-file=prod.tfvars
Module call
module "vpc" {
source = "./modules/vpc"
version = "1.2.0" # if registry module
cidr_block = var.vpc_cidr
tags = var.tags
}
Remote backend (S3 example)
terraform {
backend "s3" {
bucket = "my-tf-state"
key = "prod/network/terraform.tfstate"
region = "us-east-1"
dynamodb_table = "tf-locks"
encrypt = true
}
}
State and import
terraform import aws_instance.web i-0abc123
terraform state mv aws_instance.old aws_instance.new
terraform state rm aws_instance.orphan
terraform workspace list
terraform workspace select staging
Targeted operations
terraform plan -target=aws_instance.web
terraform apply -target=module.vpc
terraform taint aws_instance.web # force recreate on next apply
Common HCL references
| Expression | Description |
|---|---|
var.name | Input variable |
local.name | Local value |
module.vpc.vpc_id | Module output |
data.aws_ami.latest.id | Data source attribute |
aws_instance.web.id | Resource attribute |
count / for_each | Multiple resource instances |
Pro tips
- Commit
.terraform.lock.hcl— reproducible provider versions across the team - Run
planin CI on every PR; require human review beforeapplyto prod - Use
lifecycle { prevent_destroy = true }on critical resources - Prefer
for_eachovercountwhen resource identity matters - Never edit state by hand — use
state mv/rmandimport