Terraform
Website: https://www.terraform.io CLI Tool: terraform Authentication: Provider-specific (AWS, Azure, GCP credentials)
Description
Terraform is an infrastructure as code (IaC) tool for building, changing, and versioning infrastructure safely and efficiently. Define cloud and on-premises resources in human-readable configuration files. Supports multiple cloud providers including AWS, Azure, GCP, and many others.
Commands
Initialization
Initialize Working Directory
terraform init
terraform init -upgrade
terraform init -reconfigure
terraform init -backend-config=<config>
Initialize working directory, download providers and modules. Use -upgrade to update providers, -reconfigure to reconfigure backend.
Get Modules
terraform get
terraform get -update
Download and update modules.
Planning
Create Execution Plan
terraform plan
terraform plan -out=<file>
terraform plan -var="<key>=<value>"
terraform plan -var-file=<file>
terraform plan -target=<resource>
terraform plan -destroy
Generate execution plan showing what will change. Use -out to save plan, -target for specific resources.
Show Plan
terraform show
terraform show <plan-file>
terraform show -json
Display human-readable output from plan or state file.
Applying Changes
Apply Changes
terraform apply
terraform apply <plan-file>
terraform apply -auto-approve
terraform apply -var="<key>=<value>"
terraform apply -target=<resource>
Apply changes to infrastructure. Use -auto-approve to skip confirmation, -target for specific resources.
Destroy Infrastructure
terraform destroy
terraform destroy -auto-approve
terraform destroy -target=<resource>
Destroy all managed infrastructure. Use with caution!
State Management
List Resources
terraform state list
terraform state list <pattern>
List resources in state.
Show Resource
terraform state show <resource>
Show detailed resource state.
Move Resource
terraform state mv <source> <destination>
Move resource in state (rename, reorganize).
Remove Resource
terraform state rm <resource>
Remove resource from state (doesn't destroy actual resource).
Pull State
terraform state pull
Manually download and output state.
Push State
terraform state push <file>
Manually upload state.
Replace Provider
terraform state replace-provider <old> <new>
Replace provider in state.
Workspaces
List Workspaces
terraform workspace list
List all workspaces.
Create Workspace
terraform workspace new <name>
Create new workspace.
Select Workspace
terraform workspace select <name>
Switch to workspace.
Delete Workspace
terraform workspace delete <name>
Delete workspace.
Show Current Workspace
terraform workspace show
Display current workspace name.
Validation and Formatting
Validate Configuration
terraform validate
terraform validate -json
Validate configuration files for syntax errors.
Format Configuration
terraform fmt
terraform fmt -recursive
terraform fmt -check
terraform fmt -diff
Rewrite config files to canonical format. Use -recursive for subdirectories, -check to check if formatted.
Outputs
List Outputs
terraform output
terraform output <name>
terraform output -json
terraform output -raw <name>
Show output values. Use -json for JSON format, -raw for raw string output.
Import
Import Existing Resource
terraform import <resource> <id>
terraform import aws_instance.example i-1234567890abcdef0
Import existing infrastructure into Terraform state.
Providers
List Providers
terraform providers
terraform providers lock
terraform providers mirror <directory>
terraform providers schema -json
Show providers, lock versions, mirror to local directory, or show schema.
Debugging
Graph
terraform graph
terraform graph | dot -Tsvg > graph.svg
Generate visual dependency graph.
Console
terraform console
Interactive console for evaluating expressions.
Version
terraform version
Show Terraform version.
Advanced
Refresh State
terraform refresh
terraform apply -refresh-only
Update state to match real resources.
Taint Resource
terraform taint <resource>
Mark resource for recreation (deprecated, use terraform apply -replace instead).
Replace Resource
terraform apply -replace=<resource>
Force replacement of resource.
Untaint Resource
terraform untaint <resource>
Remove taint from resource (deprecated).
Force Unlock
terraform force-unlock <lock-id>
Manually unlock state (use with caution).
Examples
Basic Workflow
# Initialize project
terraform init
# Format configuration
terraform fmt -recursive
# Validate configuration
terraform validate
# Preview changes
terraform plan
# Apply changes
terraform apply
# Show outputs
terraform output
Workspace Management
# Create and switch to dev workspace
terraform workspace new dev
terraform workspace select dev
# Deploy to dev
terraform apply -var-file=dev.tfvars
# Switch to prod
terraform workspace select prod
terraform apply -var-file=prod.tfvars
State Operations
# List all resources
terraform state list
# Show specific resource
terraform state show aws_instance.example
# Move resource
terraform state mv aws_instance.old aws_instance.new
# Remove from state
terraform state rm aws_instance.example
Targeted Operations
# Plan specific resource
terraform plan -target=aws_instance.web
# Apply specific resource
terraform apply -target=aws_instance.web
# Destroy specific resource
terraform destroy -target=aws_instance.web
Import Existing Infrastructure
# Import EC2 instance
terraform import aws_instance.example i-1234567890abcdef0
# Import S3 bucket
terraform import aws_s3_bucket.example my-bucket-name
# After import, write configuration
# Then run plan to verify
terraform plan
Variable Management
# Pass variables inline
terraform apply -var="instance_type=t2.micro" -var="region=us-west-2"
# Use variable file
terraform apply -var-file=production.tfvars
# Use multiple var files
terraform apply -var-file=common.tfvars -var-file=prod.tfvars
# Environment variables (TF_VAR_)
export TF_VAR_instance_type=t2.micro
terraform apply
Debugging
# Enable detailed logs
export TF_LOG=DEBUG
terraform apply
# Save logs to file
export TF_LOG_PATH=./terraform.log
terraform apply
# View dependency graph
terraform graph | dot -Tpng > graph.png
# Interactive console
terraform console
> var.instance_type
> aws_instance.example.id
Backend Configuration
# Initialize with S3 backend
terraform init \
-backend-config="bucket=my-terraform-state" \
-backend-config="key=prod/terraform.tfstate" \
-backend-config="region=us-east-1"
# Migrate state to new backend
terraform init -migrate-state
Notes
- Configuration Files: Written in HCL (HashiCorp Configuration Language) or JSON
- State File: terraform.tfstate stores resource mappings and metadata
- Backend: Remote state storage (S3, Azure Blob, Terraform Cloud)
- Providers: Plugins for infrastructure platforms (AWS, Azure, GCP)
- Modules: Reusable Terraform configurations
- Resources: Infrastructure objects (EC2 instances, S3 buckets)
- Data Sources: Query existing infrastructure
- Variables: Input parameters for configurations
- Outputs: Export values from configuration
- Locals: Internal computed values
- Workspaces: Multiple state files for same configuration
- Plan File: Binary file containing execution plan
- Lock File: .terraform.lock.hcl ensures provider versions
- Graph: Visual representation of resource dependencies
- Taint: Mark resource for recreation (now use -replace)
- Import: Bring existing resources under Terraform management
- Provisioners: Execute scripts during resource creation/destruction
- Count/For_each: Create multiple similar resources
- Dynamic Blocks: Programmatically generate nested blocks
- State Locking: Prevent concurrent modifications
- Sensitive Data: Mark outputs as sensitive to hide in logs
- Version Constraints: Specify required Terraform and provider versions
- Best Practices:
- Use remote state storage
- Enable state locking
- Use workspaces or separate state files for environments
- Version control .tf files, not .tfstate
- Use modules for reusability
- Pin provider versions
- Use terraform fmt and validate
- Review plans before applying
Comments (0)
Add a Comment
No comments yet. Be the first to comment!