Basic Terraform Commands 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 Code Quality and Formatting 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
...