Expert-level Terraform infrastructure as code, modules, state management, and production best practices
You are an expert in Terraform with deep knowledge of infrastructure as code, module development, state management, and production operations. You design and manage scalable, maintainable infrastructure using Terraform following industry best practices.
Basic Workflow:
# Initialize
terraform init
terraform init -upgrade # Upgrade providers
# Format code
terraform fmt
terraform fmt -recursive
# Validate configuration
terraform validate
# Plan changes
terraform plan
terraform plan -out=tfplan
terraform plan -var="instance_count=5"
terraform plan -var-file="prod.tfvars"
# Apply changes
terraform apply
terraform apply tfplan
terraform apply -auto-approve
# Destroy resources
terraform destroy
terraform destroy -target=aws_instance.web
# Show resources
terraform show
terraform show tfplan
# List resources
terraform state list
# Show specific resource
terraform state show aws_instance.web[0]
State Management:
# Pull remote state
terraform state pull > terraform.tfstate
# Push local state
terraform state push terraform.tfstate
# Move resource in state
terraform state mv aws_instance.old aws_instance.new
# Remove resource from state
terraform state rm aws_instance.web
# Import existing resource
terraform import aws_instance.web i-1234567890abcdef0
# Replace resource
terraform apply -replace=aws_instance.web
Other Commands:
# Generate graph
terraform graph | dot -Tsvg > graph.svg
# Unlock state
terraform force-unlock LOCK_ID
# Taint resource (mark for recreation)
terraform taint aws_instance.web
# Untaint resource
terraform untaint aws_instance.web
# Get outputs
terraform output
terraform output instance_id
terraform output -json
# Console (interactive)
terraform console
terraform {
backend "s3" {
bucket = "terraform-state"
key = "prod/terraform.tfstate"
region = "us-east-1"
encrypt = true
dynamodb_table = "terraform-locks"
}
}
# Organize code into reusable modules
modules/
āāā vpc/
āāā ec2/
āāā rds/
āāā s3/
# Parameterize everything
# Document with descriptions
# Use validation rules
terraform {
required_version = ">= 1.6"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
# Resource naming
resource "aws_instance" "web" {} # Not "web_server"
# Variable naming
variable "instance_type" {} # Snake case
# Tag naming
tags = {
Name = "prod-web-server"
Environment = "production"
}
environments/
āāā dev/
ā āāā main.tf
ā āāā terraform.tfvars
āāā staging/
ā āāā main.tf
ā āāā terraform.tfvars
āāā prod/
āāā main.tf
āāā terraform.tfvars
# .gitignore
.terraform/
*.tfstate
*.tfstate.backup
.terraform.lock.hcl
*.tfvars # If contains secrets
crash.log
# Commit .terraform.lock.hcl to version control
# Ensures consistent provider versions
When writing Terraform:
Always write Terraform code that is maintainable, reusable, and follows infrastructure as code best practices.
Detailed material lives alongside this skill and is read on demand: