Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 37 ยท Cloud Examples

Terraform on AWS: A VPC, Load Balancer and Web Servers

Build a classic AWS web stack with Terraform: VPC, public and private subnets with cidrsubnet, security groups, an application load balancer and an auto scaling group.

Amazon Web Services is the most common target for Terraform, and a web application behind a load balancer is its classic exercise. This lesson builds the pieces one at a time: a network, firewall rules, a load balancer and a fleet of servers. The HCL is read-only here (it needs an AWS account), but the address math, subnet planning and dependency order are modeled with runnable programs.

Real AWS resources cost money (NAT gateways and load balancers bill by the hour). Use a sandbox account, set a budget alert and run terraform destroy when you finish experimenting.

The target architecture

flowchart TB
  Internet(("Internet")) --> ALB["Application Load Balancer (public subnets, 2 AZs)"]
  ALB --> ASG["Auto Scaling Group: web servers (private subnets)"]
  ASG --> NAT["NAT gateway"]
  NAT --> Internet
  ASG --> DB[("Database subnets")]

Only the load balancer is reachable from the internet; servers live in private subnets.

Network: VPC and subnets

Carve one address block into per-zone subnets with the cidrsubnet() function, so you never type CIDRs by hand:

HCL
variable "vpc_cidr" {
  type    = string
  default = "10.10.0.0/16"
}

data "aws_availability_zones" "available" {
  state = "available"
}

locals {
  azs = slice(data.aws_availability_zones.available.names, 0, 2)
}

resource "aws_vpc" "main" {
  cidr_block           = var.vpc_cidr
  enable_dns_hostnames = true
  tags                 = { Name = "web-vpc" }
}

resource "aws_subnet" "public" {
  for_each                = { for i, az in local.azs : az => i }
  vpc_id                  = aws_vpc.main.id
  availability_zone       = each.key
  cidr_block              = cidrsubnet(var.vpc_cidr, 8, each.value)       # 10.10.0.0/24, 10.10.1.0/24
  map_public_ip_on_launch = true
  tags                    = { Name = "public-${each.key}" }
}

resource "aws_subnet" "private" {
  for_each          = { for i, az in local.azs : az => i }
  vpc_id            = aws_vpc.main.id
  availability_zone = each.key
  cidr_block        = cidrsubnet(var.vpc_cidr, 8, each.value + 10)        # 10.10.10.0/24, 10.10.11.0/24
  tags              = { Name = "private-${each.key}" }
}

cidrsubnet(prefix, newbits, netnum) adds newbits bits to the mask and picks the netnum-th block. Here /16 plus 8 bits gives /24 networks. The stand-in below reproduces it with Python's ipaddress module so you can experiment.

Python cidrsubnet() stand-in

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Public subnets need an internet gateway and a route table sending 0.0.0.0/0 to it. Private subnets route outbound traffic through a NAT gateway placed in a public subnet.

HCL
resource "aws_internet_gateway" "igw" {
  vpc_id = aws_vpc.main.id
}

resource "aws_route_table" "public" {
  vpc_id = aws_vpc.main.id
  route {
    cidr_block = "0.0.0.0/0"
    gateway_id = aws_internet_gateway.igw.id
  }
}

resource "aws_route_table_association" "public" {
  for_each       = aws_subnet.public
  subnet_id      = each.value.id
  route_table_id = aws_route_table.public.id
}

Security groups

Security groups are stateful firewalls. Chain them so the servers only accept traffic from the load balancer:

HCL
resource "aws_security_group" "alb" {
  name_prefix = "alb-"
  vpc_id      = aws_vpc.main.id
  ingress {
    from_port   = 443
    to_port     = 443
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

resource "aws_security_group" "web" {
  name_prefix = "web-"
  vpc_id      = aws_vpc.main.id
  ingress {
    from_port       = 8080
    to_port         = 8080
    protocol        = "tcp"
    security_groups = [aws_security_group.alb.id]   # only the ALB may connect
  }
  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

Load balancer and auto scaling

HCL
resource "aws_lb" "web" {
  name               = "web-alb"
  load_balancer_type = "application"
  subnets            = [for s in aws_subnet.public : s.id]
  security_groups    = [aws_security_group.alb.id]
}

resource "aws_lb_target_group" "web" {
  port     = 8080
  protocol = "HTTP"
  vpc_id   = aws_vpc.main.id
  health_check { path = "/health" }
}

resource "aws_lb_listener" "https" {
  load_balancer_arn = aws_lb.web.arn
  port              = 443
  protocol          = "HTTPS"
  certificate_arn   = var.certificate_arn
  default_action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.web.arn
  }
}

resource "aws_launch_template" "web" {
  name_prefix            = "web-"
  image_id               = data.aws_ami.al2023.id
  instance_type          = "t3.small"
  vpc_security_group_ids = [aws_security_group.web.id]
  user_data              = base64encode(file("${path.module}/user-data.sh"))
}

resource "aws_autoscaling_group" "web" {
  min_size            = 2
  max_size            = 6
  vpc_zone_identifier = [for s in aws_subnet.private : s.id]
  target_group_arns   = [aws_lb_target_group.web.arn]

  launch_template {
    id      = aws_launch_template.web.id
    version = aws_launch_template.web.latest_version
  }
  lifecycle { ignore_changes = [desired_capacity] }
}

output "alb_dns_name" {
  value = aws_lb.web.dns_name
}

Terraform infers the creation order from references: the VPC first, then subnets and the internet gateway, then security groups, the load balancer and the launch template, finally the auto scaling group. The program below derives that order from a dependency table, the same way Terraform's graph does.

Python Creation order from dependencies

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Destroying runs in the reverse order, which is why you sometimes see "dependency violation" errors when something outside Terraform (an ENI left by a Lambda, say) still uses a subnet.

Production notes

  • Use a module (such as the community terraform-aws-modules/vpc/aws) instead of writing the network by hand; it covers NAT, route tables and flow logs (Registry and Versions).
  • Put the database in a third subnet tier with no internet route.
  • Keep one NAT gateway per environment in dev to save money, one per zone in production.
  • Store the state remotely, and split network from app into separate states (Remote State).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does cidrsubnet("10.10.0.0/16", 8, 1) return?

    Adding 8 bits to /16 gives /24 blocks; netnum 1 is the second block, 10.10.1.0/24.
  2. 2. Why put web servers in private subnets?

    Private subnets have no route from the internet gateway, so traffic must go through the ALB.
  3. 3. How does Terraform know to create the VPC before its subnets?

    Attribute references create implicit dependencies.
  4. 4. Why ignore_changes = [desired_capacity] on the auto scaling group?

    Otherwise every plan would try to reset the capacity the autoscaler chose.

Summary

  • Build the network with cidrsubnet() and for_each over availability zones.
  • Public subnets route to an internet gateway; private ones use a NAT gateway.
  • Chain security groups so servers accept traffic only from the load balancer.
  • An ALB plus an auto scaling group gives a resilient web tier; ignore runtime-managed attributes.
  • Prefer a tested registry module for the network and split states by component.

Next: Terraform on Azure and Google Cloud