Terraform

Infrastructure as Code - provision cloud resources declaratively across AWS, Azure, GCP with state management

TL;DR

What: An infrastructure as code tool for provisioning cloud resources.

Why: Declarative syntax, multi-cloud, state management, reproducible infrastructure.

Quick Start

Install:

brew install terraform  # macOS
# or download from terraform.io

Create main.tf:

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

provider "aws" {
  region = "us-east-1"
}

resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"

  tags = {
    Name = "example-instance"
  }
}

Run:

terraform init
terraform plan
terraform apply

Cheatsheet

CommandDescription
terraform initInitialize working directory
terraform planPreview changes
terraform applyApply changes
terraform destroyDestroy infrastructure
terraform fmtFormat code
terraform validateValidate configuration
terraform outputShow outputs
terraform state listList resources in state

Gotchas

Variables

# variables.tf
variable "instance_type" {
  description = "EC2 instance type"
  type        = string
  default     = "t2.micro"
}

# main.tf
resource "aws_instance" "example" {
  instance_type = var.instance_type
}

# terraform.tfvars
instance_type = "t3.small"

Outputs

output "instance_ip" {
  value       = aws_instance.example.public_ip
  description = "Public IP of the instance"
}

Data sources

data "aws_ami" "ubuntu" {
  most_recent = true
  filter {
    name   = "name"
    values = ["ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*"]
  }
  owners = ["099720109477"]
}

resource "aws_instance" "example" {
  ami = data.aws_ami.ubuntu.id
}

Modules

module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "5.0.0"

  name = "my-vpc"
  cidr = "10.0.0.0/16"
}

Next Steps