Initialization and Setup#
1
2
3
4
5
6
7
8
| # Initialize Terraform working directory
terraform init
# Initialize and upgrade modules
terraform init -upgrade
# Initialize with specific backend
terraform init -backend-config="config.hcl"
|
Planning and Applying#
1
2
3
4
5
6
7
8
9
10
11
| # Show execution plan
terraform plan
# Apply changes
terraform apply
terraform apply -auto-approve # Skip approval prompt
# Destroy resources
terraform destroy
terraform destroy -target aws_instance.web # Destroy specific resource
terraform destroy -auto-approve
|
Workspace Management#
1
2
3
4
5
6
7
8
9
10
11
| # List workspaces
terraform workspace list
# Create workspace
terraform workspace new dev
# Switch workspace
terraform workspace select prod
# Delete workspace
terraform workspace delete dev
|
State Management#
State Commands#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| # Show current state
terraform show
# List resources in state
terraform state list
# Move resource within state
terraform state mv aws_instance.old aws_instance.new
# Remove resource from state
terraform state rm aws_instance.web
# Pull remote state
terraform state pull
# Push state to remote
terraform state push
|
Variable Management#
Variable Definition#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| # variables.tf
variable "instance_type" {
type = string
default = "t2.micro"
description = "EC2 instance type"
}
variable "environment" {
type = string
validation {
condition = contains(["dev", "staging", "prod"], var.environment)
error_message = "Environment must be dev, staging, or prod."
}
}
|
Variable Assignment#
1
2
3
4
5
6
7
8
9
10
11
| # Command line variables
terraform plan -var="instance_type=t3.micro"
terraform apply -var="environment=dev"
# From file
terraform plan -var-file=custom.tfvars
terraform apply -var-file=prod.tfvars
# Environment variables
export TF_VAR_instance_type=t2.micro # Linux/macOS
setx TF_VAR_instance_type t2.micro # Windows
|
1
2
3
4
5
6
7
8
9
10
11
| # Format code
terraform fmt
# Validate configuration
terraform validate
# Show providers
terraform providers
# Clean up
terraform init -reconfigure
|
Module Usage#
Basic Module Structure#
1
2
3
4
5
6
7
8
| # modules/vpc/main.tf
module "vpc" {
source = "./modules/vpc"
vpc_cidr = var.vpc_cidr
subnet_cidrs = var.subnet_cidrs
vpc_name = var.vpc_name
}
|
Module Versioning#
1
2
3
4
5
6
| module "s3_bucket" {
source = "terraform-aws-modules/s3-bucket/aws"
version = "3.7.0"
bucket_name = "my-bucket"
}
|
Best Practices#
State Management
- Use remote state storage
- Enable state locking
- Use workspaces for environments
- Back up state files
Code Organization
- Use consistent naming
- Separate environments
- Modularize common patterns
- Version control all code
Security
- Use variables for sensitive data
- Store secrets in vault/KMS
- Use least privilege access
- Enable audit logging
Resource Naming
1
2
3
4
5
6
7
8
| resource "aws_instance" "web" {
tags = {
Name = "${var.project}-${var.environment}-instance"
Environment = var.environment
Project = var.project
Terraform = "true"
}
}
|
Common Patterns#
Provider Configuration#
1
2
3
4
5
6
7
8
9
10
| provider "aws" {
region = var.aws_region
default_tags {
tags = {
Environment = var.environment
Terraform = "true"
}
}
}
|
Data Sources#
1
2
3
4
5
6
7
8
9
10
| data "aws_ami" "ubuntu" {
most_recent = true
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*"]
}
owners = ["099720109477"] # Canonical
}
|
Output Values#
1
2
3
4
5
| output "instance_ip" {
value = aws_instance.web.public_ip
description = "Public IP of the web instance"
sensitive = false
}
|
Troubleshooting#
Common Issues#
1
2
3
4
5
6
7
8
9
10
| # Clean up terraform directory
rm -rf .terraform
terraform init
# Debug logging
export TF_LOG=DEBUG
export TF_LOG_PATH=terraform.log
# Force unlock state
terraform force-unlock LOCK_ID
|
State Recovery#
1
2
3
4
5
| # Backup state
terraform state pull > terraform.tfstate.backup
# Import existing resource
terraform import aws_instance.web i-1234567890abcdef0
|
Development Workflow#
Initialize Project
1
2
| terraform init
terraform workspace new dev
|
Write Configuration
1
2
| terraform fmt
terraform validate
|
Plan Changes
1
| terraform plan -out=tfplan
|
Apply Changes
Version Control
1
2
3
| git add .
git commit -m "Add new resources"
git push
|
Terraform variable assignment