Infrastructure as Code with Terraform
Terraform has become the de facto standard for infrastructure as code. Let's explore how to use it effectively.
Why Terraform?
- Cloud-agnostic: Works with AWS, Azure, GCP, and more
- Declarative: Describe what you want, not how to get there
- State management: Tracks your infrastructure
- Modular: Reusable components
Getting Started
Install Terraform:
# On macOS
brew install terraform
# On Linux
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/Basic Configuration
Create a simple AWS EC2 instance:
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = "us-west-2"
}
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
tags = {
Name = "WebServer"
}
}Terraform Workflow
- Write: Define infrastructure in
.tffiles - Plan: Preview changes with
terraform plan - Apply: Create resources with
terraform apply - Destroy: Clean up with
terraform destroy
Using Modules
Create reusable modules:
module "vpc" {
source = "./modules/vpc"
cidr_block = "10.0.0.0/16"
name = "production-vpc"
}State Management
Store state remotely for team collaboration:
terraform {
backend "s3" {
bucket = "my-terraform-state"
key = "prod/terraform.tfstate"
region = "us-west-2"
}
}Best Practices
- Use workspaces for different environments
- Implement remote state with locking
- Use variables for flexibility
- Create modules for reusability
- Version your modules properly
- Use
.tfvarsfiles for sensitive data
Conclusion
Terraform enables you to manage infrastructure efficiently and consistently. Start small, use modules, and always plan before applying!