Terraform Documentation
What is Terraform?
Terraform is a tool for building, changing, and versioning infrastructure safely and efficiently. Terraform can manage existing and popular service providers as well as custom in-house solutions.
Key Features
- 🏗️ Infrastructure as Code - Define infrastructure using declarative configuration files
- 🔄 Execution Plans - Preview changes before applying them
- 📦 Resource Graph - Build resources in parallel for maximum efficiency
- 🔧 Change Automation - Apply complex changesets with minimal human interaction
- 🌍 Multi-Cloud - Support for AWS, Azure, GCP, and 100+ providers
- 📝 Version Control - Track infrastructure changes in Git
Core Concepts
Configuration Files (.tf)
Terraform uses text files to describe infrastructure. These files use HCL (HashiCorp Configuration Language)
syntax and have a .tf extension.
Providers
Providers are plugins that Terraform uses to interact with cloud providers, SaaS providers, and other APIs. Examples: AWS, Azure, GCP, Docker, Kubernetes.
Resources
Resources are the most important element in Terraform. Each resource block describes one or more infrastructure objects such as virtual networks, compute instances, or higher-level components.
State
Terraform must store state about your managed infrastructure and configuration. This state is used to map real world resources to your configuration and keep track of metadata.
Modules
Modules are containers for multiple resources that are used together. They allow you to organize your code, reuse infrastructure, and create abstractions.
Variables
Variables allow you to customize aspects of Terraform modules without altering the module's source code. They make your configuration more flexible and reusable.
Installation
Linux
# Install using package manager
# Ubuntu/Debian
sudo apt-get update && sudo apt-get install -y gnupg software-properties-common curl
curl -fsSL https://apt.releases.hashicorp.com/gpg | sudo apt-key add -
sudo apt-add-repository "deb [arch=amd64] https://apt.releases.hashicorp.com $(lsb_release -cs) main"
sudo apt-get update && sudo apt-get install terraform
# Using wget
wget https://releases.hashicorp.com/terraform/1.6.0/terraform_1.6.0_linux_amd64.zip
unzip terraform_1.6.0_linux_amd64.zip
sudo mv terraform /usr/local/bin/
# Verify installation
terraform version
macOS
# Using Homebrew
brew tap hashicorp/tap
brew install hashicorp/tap/terraform
# Or using tfenv (Terraform version manager)
brew install tfenv
tfenv install latest
tfenv use latest
# Verify installation
terraform version
Windows
# Using Chocolatey
choco install terraform
# Or download from: https://www.terraform.io/downloads
# Extract and add to PATH
# Verify installation
terraform version
Quick Start Example
Let's create a simple AWS EC2 instance using Terraform:
1. Create main.tf
# Configure AWS Provider
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = "us-east-1"
}
# Create EC2 instance
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
tags = {
Name = "HelloWorld"
}
}
2. Initialize Terraform
# Initialize Terraform and download providers
terraform init
3. Plan Changes
# Preview changes before applying
terraform plan
4. Apply Changes
# Create the infrastructure
terraform apply
# Type 'yes' to confirm
5. Verify Resources
# List all resources
terraform show
# Get resource state
terraform state list
# View specific resource
terraform state show aws_instance.web
6. Destroy Infrastructure
# Remove all resources
terraform destroy
# Type 'yes' to confirm
Common Terraform Commands
Basic Commands
# Initialize Terraform
terraform init
# Validate configuration
terraform validate
# Format configuration files
terraform fmt
# Show plan
terraform plan
# Apply changes
terraform apply
# Apply without prompt
terraform apply -auto-approve
# Destroy infrastructure
terraform destroy
# Show current state
terraform show
# List resources in state
terraform state list
State Management
# Show specific resource
terraform state show aws_instance.web
# Move resource
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
Output Commands
# Show outputs
terraform output
# Show specific output
terraform output instance_id
# Show outputs in JSON
terraform output -json
Project Structure
A typical Terraform project structure:
terraform-project/
├── main.tf # Main configuration
├── variables.tf # Input variables
├── outputs.tf # Output values
├── terraform.tfvars # Variable values
├── terraform.tfstate # State file (don't commit)
├── terraform.tfstate.backup # State backup
└── .terraform/ # Provider plugins (don't commit)
Basic Configuration Example
variables.tf
variable "region" {
description = "AWS region"
type = string
default = "us-east-1"
}
variable "instance_type" {
description = "EC2 instance type"
type = string
default = "t2.micro"
}
variable "tags" {
description = "Tags to apply to resources"
type = map(string)
default = {
Environment = "dev"
Project = "example"
}
}
main.tf
terraform {
required_version = ">= 1.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
backend "s3" {
bucket = "my-terraform-state"
key = "terraform.tfstate"
region = "us-east-1"
}
}
provider "aws" {
region = var.region
}
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = var.instance_type
tags = var.tags
}
outputs.tf
output "instance_id" {
description = "ID of the EC2 instance"
value = aws_instance.web.id
}
output "instance_public_ip" {
description = "Public IP address of the EC2 instance"
value = aws_instance.web.public_ip
}
output "instance_public_dns" {
description = "Public DNS name of the EC2 instance"
value = aws_instance.web.public_dns
}
terraform.tfvars
region = "us-east-1"
instance_type = "t2.micro"
tags = {
Environment = "production"
Project = "web-app"
ManagedBy = "Terraform"
}
Workflow
- Write - Create Terraform configuration files
- Initialize - Run
terraform initto download providers - Plan - Run
terraform planto preview changes - Apply - Run
terraform applyto create/update infrastructure - Verify - Check the created resources
- Modify - Update configuration files as needed
- Destroy - Run
terraform destroywhen done
Why Use Terraform?
Infrastructure as Code Benefits
- ✅ Version Control - Track infrastructure changes in Git
- ✅ Reproducibility - Create identical environments easily
- ✅ Collaboration - Multiple team members can work together
- ✅ Documentation - Code serves as documentation
- ✅ Disaster Recovery - Recreate infrastructure from code
- ✅ Cost Optimization - Easily test and destroy resources
Common Use Cases
- 🏢 Cloud Infrastructure - Provision resources on AWS, Azure, GCP
- 🐳 Container Orchestration - Manage Kubernetes, Docker Swarm
- 🗄️ Database Setup - Configure RDS, Cloud SQL, Azure Database
- 🌐 Networking - Set up VPCs, subnets, load balancers
- 🔐 Security - Configure IAM roles, security groups, policies
- 📊 Monitoring - Set up CloudWatch, Stackdriver, Azure Monitor
Next Steps
Continue learning with our detailed guides:
- Core Concepts - Deep dive into Terraform fundamentals
- Providers & Resources - Working with providers and resources
- State Management - Understanding and managing Terraform state
- Modules - Creating reusable modules
- AWS Setup - Complete AWS setup guide
- GCP Setup - Complete GCP setup guide
- Best Practices - Production-ready practices