Infrastructure as Code
Define infrastructure in files. Review, version, repeat.
Basic Structure
# main.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = "us-east-1"
}
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t3.micro"
tags = {
Name = "web-server"
}
}
Common Commands
# Initialize (download providers)
terraform init
# Preview changes
terraform plan
# Apply changes
terraform apply
# Destroy resources
terraform destroy
Variables
# variables.tf
variable "environment" {
description = "Environment name"
type = string
default = "dev"
}
variable "instance_type" {
type = string
default = "t3.micro"
}
# Use them
resource "aws_instance" "web" {
instance_type = var.instance_type
tags = {
Environment = var.environment
}
}
Outputs
output "instance_ip" {
value = aws_instance.web.public_ip
}
Remote State
Don't commit state files:
terraform {
backend "s3" {
bucket = "my-terraform-state"
key = "prod/terraform.tfstate"
region = "us-east-1"
}
}
Modules
Reusable components:
module "vpc" {
source = "./modules/vpc"
cidr = "10.0.0.0/16"
}
module "web" {
source = "./modules/ec2"
vpc_id = module.vpc.id
subnet_id = module.vpc.public_subnet_id
}
Tips
- Always run
planbeforeapply - Use workspaces for environments
- Keep modules small and focused
- Lock provider versions
