Terraform Commands Reference Sheet

Pavel 08.12.2025 18:59 4 просмотров

Course: Terraform for Beginners (ADV-IT)
Language: Russian
Updated: November 26, 2025


1. Basic Commands

# Check version
terraform version

# Validate configuration
terraform validate

# Format code
terraform fmt
terraform fmt -recursive

# Initialize working directory
terraform init
terraform init -upgrade
terraform init -reconfigure

# Show current state
terraform show
terraform show -json

# Refresh state
terraform refresh

# Display state list
terraform state list
terraform state list aws_instance.*

2. Planning & Applying

# Generate and show execution plan
terraform plan
terraform plan -out=tfplan

# Apply changes
terraform apply
terraform apply tfplan
terraform apply -auto-approve

# Apply with variables
terraform apply -var="region=us-west-2"
terraform apply -var-file="prod.tfvars"

# Apply specific resources
terraform apply -target=aws_instance.web
terraform apply -target='module.vpc'

# Destroy infrastructure
terraform destroy
terraform destroy -auto-approve
terraform destroy -target=aws_instance.web

3. State Management

# List resources
terraform state list

# Show resource details
terraform state show aws_instance.web

# Remove from state (doesn't delete)
terraform state rm aws_instance.web

# Move/rename resource
terraform state mv aws_instance.old aws_instance.new

# Pull current state
terraform state pull > backup.tfstate

# Push state
terraform state push backup.tfstate

# Lock state
terraform state lock <id>

# Unlock state
terraform state unlock <id>

4. Variables & Outputs

# Use variables from file
terraform apply -var-file="dev.tfvars"

# Override variable
terraform apply -var="instance_type=t2.large"

# Set environment variable
export TF_VAR_region="eu-west-1"

# View outputs
terraform output
terraform output -json

# Single output
terraform output instance_id

# Save outputs to file
terraform output -json > outputs.json

5. Import & Taint

# Import existing resource
terraform import aws_instance.web i-1234567890abcdef0

# Taint resource (mark for recreation)
terraform taint aws_instance.web

# Untaint resource
terraform untaint aws_instance.web

# Taint module
terraform taint 'module.vpc.aws_subnet.main'

6. Workspaces

# List workspaces
terraform workspace list

# Create workspace
terraform workspace new dev
terraform workspace new staging
terraform workspace new prod

# Select workspace
terraform workspace select prod

# Show current workspace
terraform workspace show

# Delete workspace
terraform workspace delete dev

# Apply to specific workspace
terraform apply -var-file="prod.tfvars"  # In prod workspace

7. Backend & Remote State

# Initialize with backend
terraform init

# Switch to local backend
terraform init -migrate-state -backend-config="skip_credentials_validation=true"

# Reconfigure backend
terraform init -reconfigure -backend-config="key=prod/terraform.tfstate"

# Backend configuration
terraform backend config -backend-config="bucket=new-bucket"

8. Module Commands

# Get modules
terraform get
terraform get -update

# Validate module
terraform validate

# List modules
terraform state list module.*

# Destroy module
terraform destroy -target='module.vpc'

# Debug module
terraform console
# In console: module.vpc.vpc_id

9. Graph & Documentation

# Generate dependency graph
terraform graph

# Export graph as PNG
terraform graph | dot -Tpng > graph.png

# Export graph as SVG
terraform graph | dot -Tsvg > graph.svg

# Show input/output variables
terraform console
# var.region
# output.instance_id

10. Debug & Logs

# Enable detailed logging
export TF_LOG=DEBUG

# Save logs to file
export TF_LOG_PATH=terraform.log

# Disable logging
unset TF_LOG
unset TF_LOG_PATH

# Dry-run with debug
terraform plan -var-file="dev.tfvars" > plan.log 2>&1

# Validate with details
terraform validate -json

11. Provisioners

# Local execution
provisioner "local-exec" {
  command = "echo ${self.public_ip} >> ips.txt"
}

# Remote execution
provisioner "remote-exec" {
  inline = [
    "sudo apt-get update",
    "sudo apt-get install -y nginx"
  ]
}

# File provisioner
provisioner "file" {
  source      = "app.conf"
  destination = "/tmp/app.conf"
}

12. Common Workflows

Development Workflow

# 1. Write configuration
vim main.tf

# 2. Initialize
terraform init

# 3. Validate
terraform validate
terraform fmt

# 4. Plan
terraform plan -var-file="dev.tfvars"

# 5. Apply
terraform apply -var-file="dev.tfvars"

# 6. Clean up
terraform destroy -var-file="dev.tfvars"

Production Deployment

# 1. Create plan
terraform plan -var-file="prod.tfvars" -out=tfplan

# 2. Review plan
cat tfplan

# 3. Apply
terraform apply tfplan

# 4. Verify
terraform output -json

# 5. Store state
aws s3 cp terraform.tfstate s3://backup-bucket/

State Recovery

# 1. Backup current state
terraform state pull > backup.tfstate

# 2. View state
cat backup.tfstate

# 3. Restore if needed
terraform state push backup.tfstate

# 4. Verify
terraform state list

13. Useful Aliases

# Add to ~/.bashrc or ~/.zshrc
alias tf='terraform'
alias tfi='terraform init'
alias tfv='terraform validate'
alias tfp='terraform plan'
alias tfa='terraform apply'
alias tfd='terraform destroy'
alias tfo='terraform output'
alias tfr='terraform refresh'
alias tfs='terraform state'
alias tfgraph='terraform graph | dot -Tsvg > graph.svg'

# Usage
tf plan
tfa -var-file="prod.tfvars"
tfs list

14. Configuration Examples

Simple Variable Usage

# terraform.tfvars
aws_region = "us-west-2"
environment = "prod"
instance_count = 3

# Command
terraform apply -var-file="terraform.tfvars"

Multiple Variables Files

# Default
terraform apply -var-file="terraform.tfvars"

# Override with environment-specific
terraform apply \
  -var-file="terraform.tfvars" \
  -var-file="prod.tfvars"

# Override with CLI
terraform apply \
  -var-file="terraform.tfvars" \
  -var="instance_type=t2.large"

Complex Variable Types

# List variable
terraform apply -var='instance_ids=["i-123", "i-456"]'

# Map variable
terraform apply -var='tags={Name=web,Env=prod}'

# Object variable
terraform apply -var='config={enabled=true,port=8080}'

15. Troubleshooting

Common Issues

# Error: Required argument missing
# Solution: Check required variables in variables.tf

# Error: Resource already exists
# Solution: terraform import or terraform state rm

# Error: Invalid resource reference
# Solution: Check syntax - should be resource_type.name.attribute

# Error: Timeout
# Solution: Increase timeout with -lock-timeout=5m

# Error: State lock
# Solution: Check who has lock, or force unlock with caution
terraform force-unlock <LOCK_ID>

16. Best Practices

# ✅ DO
terraform validate           # Always validate
terraform fmt               # Format code
terraform plan -out=tfplan  # Save plans
terraform state pull        # Backup state
export TF_LOG=WARN          # Enable warnings

# ❌ DON'T
terraform destroy -auto-approve  # Without confirmation
rm terraform.tfstate            # Delete state manually
git add terraform.tfstate       # Commit state to Git
terraform apply                 # Without reviewing plan

17. Performance Tuning

# Parallel operations (default: 10)
terraform apply -parallelism=20

# Skip refresh
terraform plan -refresh=false

# Incremental planning
terraform apply -target='module.vpc'

# Lock timeout
terraform apply -lock-timeout=10m

# Compress state
terraform state pull | gzip > state.gz

18. Safety Features

# Prevent destruction
lifecycle {
  prevent_destroy = true
}

# Require approval for destroy
terraform destroy  # Manual confirmation

# Lock state for multi-user
terraform state lock <resource-id>

# Backup before operations
terraform state pull > backup.tfstate

# Dry-run
terraform plan -json > plan.json

Quick Reference Table

Task Command
Check Terraform version terraform version
Initialize directory terraform init
Validate syntax terraform validate
Format code terraform fmt -recursive
Create plan terraform plan -out=tfplan
Apply changes terraform apply tfplan
Destroy all terraform destroy -auto-approve
Show state terraform show
List resources terraform state list
View output terraform output
Import resource terraform import aws_instance.web <id>
Taint resource terraform taint aws_instance.web
Create workspace terraform workspace new prod
Switch workspace terraform workspace select prod
View graph terraform graph \| dot -Tsvg > graph.svg

For more help: terraform -help or visit https://www.terraform.io/docs/

Комментарии (0)

Для добавления комментария необходимо войти в аккаунт

Войти / Зарегистрироваться