Labs · DevOps
Lab: Build a Multi-AZ 3-Tier Stack with Terraform: Internet-Facing ALB, Web ASG, Internal ALB, App ASG, Bastion, Two NAT Gateways, Multi-AZ RDS Standby and a Read Replica
Course: DevOps · Chapter 46: Terraform 3-Tier Architecture Multi-AZ with ALBs Auto Scaling Bastion NAT and RDS · Lesson: 46.1 Multi-AZ 3-tier architecture: the picture and the file layout
Chapter 46 explains every file in eight lessons; this lab is the step-by-step run sheet for the whole stack.
Chala mitrano! Ek poorna zone band zhala tari shop chalu rahila pahije. Aaj production sarkha multi-AZ stack banvuya, ani shevti destroy.
Suppose we are…
Suppose we are on a Netflix-style platform team running an online shop that must stay up even if one whole AWS data centre zone goes down. Every tier therefore runs in two Availability Zones, AZ-a and AZ-b. Users reach an internet-facing load balancer in the public subnets; it sends traffic to a web Auto Scaling group in private web subnets; the web servers call an internal load balancer that spreads requests over an app Auto Scaling group; and the app writes to an RDS database that has a standby copy in the other zone plus a read replica for reports. Admins enter only through a bastion jump server. This lesson is the map; each next lesson builds one part of it.
Goal of this lab
By the end you will have:
- Every tier in two Availability Zones: web and app Auto Scaling groups behind an external and an internal ALB.
- A bastion reachable only from your IP, and app servers reachable only through it.
- A Multi-AZ RDS primary with a standby and a read replica, and the whole stack destroyed at the end.
What you need
- Terraform 1.6 or newer (
terraform version). - AWS CLI v2 signed in to your own AWS account with an IAM user or SSO role that may create these resources (
aws sts get-caller-identityworks). Never use the root user, and never paste access keys into .tf files. - Region Mumbai (
ap-south-1) is used; changeregionif you prefer another. - Your public IP (
curl -s https://checkip.amazonaws.com). - About 2.5 hours (the RDS primary and replica take 15–25 minutes).
Cost and cleanup
Two NAT gateways, two ALBs, several instances and two RDS instances (one with a standby) are billed every hour. This is the most expensive lab in the course: finish it the same day. Small charges are possible even on the free tier. Finish the lab in one sitting and always run the Clean up part at the end.
Part 1: Key pair, layout, versions and variables
Create the SSH key on your laptop. The private key never leaves your laptop:
ssh-keygen -t ed25519 -f ~/.ssh/shop3t -N "" chmod 400 ~/.ssh/shop3t mkdir -p three-tier-multi-az/userdata && cd three-tier-multi-azWhat you should see: at the end of Part 7 you will have:
three-tier-multi-az/ ├── versions.tf ├── variables.tf ├── network.tf # VPC, 8 subnets, IGW, 2 NAT, route tables ├── security.tf # 6 security groups chained ├── bastion.tf # key pair + jump server ├── web.tf # internet-facing ALB + web launch template + web ASG ├── app.tf # internal ALB + app launch template + app ASG ├── db.tf # DB subnet group + Multi-AZ RDS + read replica ├── outputs.tf └── userdata/ ├── web.sh.tftpl └── app.shCreate
versions.tf:versions.tf
terraform { required_version = ">= 1.6" required_providers { aws = { source = "hashicorp/aws" version = "~> 5.0" } } } provider "aws" { region = var.region }Create
variables.tf:variables.tf
variable "region" { type = string default = "ap-south-1" } variable "project" { type = string default = "shop3t" } variable "vpc_cidr" { type = string default = "10.40.0.0/16" } variable "my_ip_cidr" { description = "Your public IP with /32, the only address allowed to SSH to the bastion" type = string validation { condition = can(cidrhost(var.my_ip_cidr, 0)) && endswith(var.my_ip_cidr, "/32") error_message = "Give a single address such as 203.0.113.10/32." } } variable "public_key_path" { type = string default = "~/.ssh/shop3t.pub" } variable "instance_type" { type = string default = "t3.micro" } variable "db_username" { type = string default = "appadmin" }Init:
terraform initWhat you should see:
Terraform has been successfully initialized!
Part 2: VPC, 8 subnets, internet gateway, 2 NAT gateways and route tables
Create
network.tf:network.tf
data "aws_availability_zones" "available" { state = "available" } locals { azs = { a = data.aws_availability_zones.available.names[0] b = data.aws_availability_zones.available.names[1] } idx = { a = 0, b = 1 } } resource "aws_vpc" "main" { cidr_block = var.vpc_cidr enable_dns_support = true enable_dns_hostnames = true tags = { Name = "${var.project}-vpc" } } resource "aws_internet_gateway" "igw" { vpc_id = aws_vpc.main.id tags = { Name = "${var.project}-igw" } } resource "aws_subnet" "public" { for_each = local.azs vpc_id = aws_vpc.main.id cidr_block = cidrsubnet(var.vpc_cidr, 8, 1 + local.idx[each.key]) availability_zone = each.value map_public_ip_on_launch = true tags = { Name = "${var.project}-public-${each.key}" } } resource "aws_subnet" "web" { for_each = local.azs vpc_id = aws_vpc.main.id cidr_block = cidrsubnet(var.vpc_cidr, 8, 11 + local.idx[each.key]) availability_zone = each.value tags = { Name = "${var.project}-web-${each.key}" } } resource "aws_subnet" "app" { for_each = local.azs vpc_id = aws_vpc.main.id cidr_block = cidrsubnet(var.vpc_cidr, 8, 21 + local.idx[each.key]) availability_zone = each.value tags = { Name = "${var.project}-app-${each.key}" } } resource "aws_subnet" "db" { for_each = local.azs vpc_id = aws_vpc.main.id cidr_block = cidrsubnet(var.vpc_cidr, 8, 31 + local.idx[each.key]) availability_zone = each.value tags = { Name = "${var.project}-db-${each.key}" } } resource "aws_eip" "nat" { for_each = local.azs domain = "vpc" } resource "aws_nat_gateway" "nat" { for_each = local.azs allocation_id = aws_eip.nat[each.key].id subnet_id = aws_subnet.public[each.key].id depends_on = [aws_internet_gateway.igw] tags = { Name = "${var.project}-nat-${each.key}" } } 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 } tags = { Name = "${var.project}-rt-public" } } resource "aws_route_table" "private" { for_each = local.azs vpc_id = aws_vpc.main.id route { cidr_block = "0.0.0.0/0" nat_gateway_id = aws_nat_gateway.nat[each.key].id } tags = { Name = "${var.project}-rt-private-${each.key}" } } resource "aws_route_table" "db" { vpc_id = aws_vpc.main.id tags = { Name = "${var.project}-rt-db" } } resource "aws_route_table_association" "public" { for_each = aws_subnet.public subnet_id = each.value.id route_table_id = aws_route_table.public.id } resource "aws_route_table_association" "web" { for_each = aws_subnet.web subnet_id = each.value.id route_table_id = aws_route_table.private[each.key].id } resource "aws_route_table_association" "app" { for_each = aws_subnet.app subnet_id = each.value.id route_table_id = aws_route_table.private[each.key].id } resource "aws_route_table_association" "db" { for_each = aws_subnet.db subnet_id = each.value.id route_table_id = aws_route_table.db.id }Validate and review only the network (put your IP in place of <your-ip>):
terraform validate terraform plan -var my_ip_cidr=<your-ip>/32 -target=aws_route_table_association.db -target=aws_route_table_association.app -target=aws_route_table_association.web -target=aws_route_table_association.publicWhat you should see: 8 subnets, 2 NAT gateways, 4 route tables and 8 associations.
Part 3: Security group chain
Create
security.tf:security.tf
resource "aws_security_group" "ext_alb" { name = "${var.project}-ext-alb" vpc_id = aws_vpc.main.id } resource "aws_security_group" "web" { name = "${var.project}-web" vpc_id = aws_vpc.main.id } resource "aws_security_group" "int_alb" { name = "${var.project}-int-alb" vpc_id = aws_vpc.main.id } resource "aws_security_group" "app" { name = "${var.project}-app" vpc_id = aws_vpc.main.id } resource "aws_security_group" "db" { name = "${var.project}-db" vpc_id = aws_vpc.main.id } resource "aws_security_group" "bastion" { name = "${var.project}-bastion" vpc_id = aws_vpc.main.id } resource "aws_vpc_security_group_ingress_rule" "ext_alb_http" { security_group_id = aws_security_group.ext_alb.id cidr_ipv4 = "0.0.0.0/0" ip_protocol = "tcp" from_port = 80 to_port = 80 } resource "aws_vpc_security_group_ingress_rule" "web_from_ext_alb" { security_group_id = aws_security_group.web.id referenced_security_group_id = aws_security_group.ext_alb.id ip_protocol = "tcp" from_port = 80 to_port = 80 } resource "aws_vpc_security_group_ingress_rule" "int_alb_from_web" { security_group_id = aws_security_group.int_alb.id referenced_security_group_id = aws_security_group.web.id ip_protocol = "tcp" from_port = 80 to_port = 80 } resource "aws_vpc_security_group_ingress_rule" "app_from_int_alb" { security_group_id = aws_security_group.app.id referenced_security_group_id = aws_security_group.int_alb.id ip_protocol = "tcp" from_port = 8080 to_port = 8080 } resource "aws_vpc_security_group_ingress_rule" "db_from_app" { security_group_id = aws_security_group.db.id referenced_security_group_id = aws_security_group.app.id ip_protocol = "tcp" from_port = 3306 to_port = 3306 } resource "aws_vpc_security_group_ingress_rule" "bastion_ssh" { security_group_id = aws_security_group.bastion.id cidr_ipv4 = var.my_ip_cidr ip_protocol = "tcp" from_port = 22 to_port = 22 } resource "aws_vpc_security_group_ingress_rule" "web_ssh_from_bastion" { security_group_id = aws_security_group.web.id referenced_security_group_id = aws_security_group.bastion.id ip_protocol = "tcp" from_port = 22 to_port = 22 } resource "aws_vpc_security_group_ingress_rule" "app_ssh_from_bastion" { security_group_id = aws_security_group.app.id referenced_security_group_id = aws_security_group.bastion.id ip_protocol = "tcp" from_port = 22 to_port = 22 } resource "aws_vpc_security_group_egress_rule" "all" { for_each = toset(["ext_alb", "web", "int_alb", "app", "bastion"]) security_group_id = local.sg_ids[each.key] cidr_ipv4 = "0.0.0.0/0" ip_protocol = "-1" } locals { sg_ids = { ext_alb = aws_security_group.ext_alb.id web = aws_security_group.web.id int_alb = aws_security_group.int_alb.id app = aws_security_group.app.id bastion = aws_security_group.bastion.id } }Validate and check where the world is allowed:
terraform validate grep -n "0.0.0.0/0" security.tfWhat you should see: only on the external ALB ingress and on egress rules.
Part 4: Bastion jump server
Create
bastion.tf:bastion.tf
data "aws_ami" "al2023" { most_recent = true owners = ["amazon"] filter { name = "name" values = ["al2023-ami-2023.*-x86_64"] } } resource "aws_key_pair" "ops" { key_name = "${var.project}-ops" public_key = file(pathexpand(var.public_key_path)) } resource "aws_instance" "bastion" { ami = data.aws_ami.al2023.id instance_type = "t3.micro" subnet_id = aws_subnet.public["a"].id vpc_security_group_ids = [aws_security_group.bastion.id] key_name = aws_key_pair.ops.key_name metadata_options { http_tokens = "required" } tags = { Name = "${var.project}-bastion" } }
Part 5: Internet-facing ALB and web Auto Scaling group
Create
web.tf:web.tf
resource "aws_lb" "external" { name = "${var.project}-ext-alb" load_balancer_type = "application" internal = false security_groups = [aws_security_group.ext_alb.id] subnets = [for s in aws_subnet.public : s.id] } resource "aws_lb_target_group" "web" { name = "${var.project}-web-tg" port = 80 protocol = "HTTP" vpc_id = aws_vpc.main.id health_check { path = "/" matcher = "200" } } resource "aws_lb_listener" "external_http" { load_balancer_arn = aws_lb.external.arn port = 80 protocol = "HTTP" default_action { type = "forward" target_group_arn = aws_lb_target_group.web.arn } } resource "aws_launch_template" "web" { name_prefix = "${var.project}-web-" image_id = data.aws_ami.al2023.id instance_type = var.instance_type key_name = aws_key_pair.ops.key_name vpc_security_group_ids = [aws_security_group.web.id] metadata_options { http_tokens = "required" } user_data = base64encode(templatefile("${path.module}/userdata/web.sh.tftpl", { app_lb_dns = aws_lb.internal.dns_name })) } resource "aws_autoscaling_group" "web" { name = "${var.project}-web-asg" min_size = 2 desired_capacity = 2 max_size = 4 vpc_zone_identifier = [for s in aws_subnet.web : s.id] target_group_arns = [aws_lb_target_group.web.arn] health_check_type = "ELB" health_check_grace_period = 120 launch_template { id = aws_launch_template.web.id version = aws_launch_template.web.latest_version } instance_refresh { strategy = "Rolling" } tag { key = "Name" value = "${var.project}-web" propagate_at_launch = true } } resource "aws_autoscaling_policy" "web_cpu" { name = "web-cpu-60" autoscaling_group_name = aws_autoscaling_group.web.name policy_type = "TargetTrackingScaling" target_tracking_configuration { predefined_metric_specification { predefined_metric_type = "ASGAverageCPUUtilization" } target_value = 60 } }Create
userdata/web.sh.tftpl:userdata/web.sh.tftpl
#!/bin/bash dnf install -y nginx echo "web tier: $(hostname)" > /usr/share/nginx/html/index.html cat > /etc/nginx/default.d/app.conf <<'CONF' location /api/ { proxy_pass http://${app_lb_dns}/; } CONF systemctl enable --now nginxValidate:
terraform validate
Part 6: Internal ALB and app Auto Scaling group
Create
app.tf:app.tf
resource "aws_lb" "internal" { name = "${var.project}-int-alb" load_balancer_type = "application" internal = true security_groups = [aws_security_group.int_alb.id] subnets = [for s in aws_subnet.app : s.id] } resource "aws_lb_target_group" "app" { name = "${var.project}-app-tg" port = 8080 protocol = "HTTP" vpc_id = aws_vpc.main.id health_check { path = "/" port = "8080" matcher = "200" } } resource "aws_lb_listener" "internal_http" { load_balancer_arn = aws_lb.internal.arn port = 80 protocol = "HTTP" default_action { type = "forward" target_group_arn = aws_lb_target_group.app.arn } } resource "aws_launch_template" "app" { name_prefix = "${var.project}-app-" image_id = data.aws_ami.al2023.id instance_type = var.instance_type key_name = aws_key_pair.ops.key_name vpc_security_group_ids = [aws_security_group.app.id] metadata_options { http_tokens = "required" } user_data = filebase64("${path.module}/userdata/app.sh") } resource "aws_autoscaling_group" "app" { name = "${var.project}-app-asg" min_size = 2 desired_capacity = 2 max_size = 6 vpc_zone_identifier = [for s in aws_subnet.app : s.id] target_group_arns = [aws_lb_target_group.app.arn] health_check_type = "ELB" health_check_grace_period = 120 launch_template { id = aws_launch_template.app.id version = aws_launch_template.app.latest_version } instance_refresh { strategy = "Rolling" } tag { key = "Name" value = "${var.project}-app" propagate_at_launch = true } } resource "aws_autoscaling_policy" "app_cpu" { name = "app-cpu-60" autoscaling_group_name = aws_autoscaling_group.app.name policy_type = "TargetTrackingScaling" target_tracking_configuration { predefined_metric_specification { predefined_metric_type = "ASGAverageCPUUtilization" } target_value = 60 } }Create
userdata/app.sh:userdata/app.sh
#!/bin/bash mkdir -p /opt/app echo "app tier: $(hostname)" > /opt/app/index.html cat > /etc/systemd/system/app.service <<'UNIT' [Unit] Description=demo app [Service] ExecStart=/usr/bin/python3 -m http.server 8080 --directory /opt/app Restart=always [Install] WantedBy=multi-user.target UNIT systemctl daemon-reload systemctl enable --now appValidate:
terraform validate
Part 7: DB subnet group, Multi-AZ RDS, read replica and outputs
Create
db.tf:db.tf
resource "aws_db_subnet_group" "db" { name = "${var.project}-db" subnet_ids = [for s in aws_subnet.db : s.id] tags = { Name = "${var.project}-db-subnets" } } resource "aws_db_instance" "primary" { identifier = "${var.project}-mysql" engine = "mysql" engine_version = "8.0" instance_class = "db.t3.micro" allocated_storage = 20 max_allocated_storage = 100 storage_type = "gp3" storage_encrypted = true db_name = "shopdb" username = var.db_username manage_master_user_password = true db_subnet_group_name = aws_db_subnet_group.db.name vpc_security_group_ids = [aws_security_group.db.id] multi_az = true publicly_accessible = false backup_retention_period = 7 backup_window = "18:30-19:30" maintenance_window = "sun:20:00-sun:21:00" skip_final_snapshot = true deletion_protection = false } resource "aws_db_instance" "replica" { identifier = "${var.project}-mysql-replica" replicate_source_db = aws_db_instance.primary.identifier instance_class = "db.t3.micro" storage_encrypted = true vpc_security_group_ids = [aws_security_group.db.id] availability_zone = local.azs["b"] publicly_accessible = false skip_final_snapshot = true }Create
outputs.tf:outputs.tf
output "app_url" { value = "http://${aws_lb.external.dns_name}" } output "internal_alb_dns" { value = aws_lb.internal.dns_name } output "bastion_public_ip" { value = aws_instance.bastion.public_ip } output "db_writer_endpoint" { value = aws_db_instance.primary.address } output "db_reader_endpoint" { value = aws_db_instance.replica.address } output "db_secret_arn" { value = aws_db_instance.primary.master_user_secret[0].secret_arn }Format and validate everything:
terraform fmt -recursive terraform validateWhat you should see:
Success! The configuration is valid.
Part 8: Apply and test end to end
Plan with your IP, read it, then apply that plan (RDS takes the longest):
terraform plan -var my_ip_cidr=<your-ip>/32 -out tfplan terraform apply tfplanTest browser → external ALB → web → internal ALB → app:
curl -s $(terraform output -raw app_url) curl -s $(terraform output -raw app_url)/api/What you should see: both tiers answering:
$ terraform apply -var my_ip_cidr=203.0.113.10/32 Apply complete! Resources: 62 added, 0 changed, 0 destroyed. Outputs: app_url = "http://shop3t-ext-alb-123456.ap-south-1.elb.amazonaws.com" bastion_public_ip = "13.xxx.xxx.xxx" db_reader_endpoint = "shop3t-mysql-replica.cxxxx.ap-south-1.rds.amazonaws.com" db_writer_endpoint = "shop3t-mysql.cxxxx.ap-south-1.rds.amazonaws.com" $ curl -s $(terraform output -raw app_url) web tier: ip-10-40-11-52.ap-south-1.compute.internal $ curl -s $(terraform output -raw app_url)/api/ app tier: ip-10-40-22-81.ap-south-1.compute.internalRun the
/api/curl several times.What you should see: app answers from private IPs in both zones.
Jump through the bastion to one app server (take a private app IP from the EC2 console):
ssh-add ~/.ssh/shop3t ssh -J ec2-user@$(terraform output -raw bastion_public_ip) ec2-user@<app-private-ip> "systemctl is-active app"What you should see:
active. The private key stayed on your laptop; never copy it to the bastion.Check the database setup:
aws rds describe-db-instances --query "DBInstances[].[DBInstanceIdentifier,MultiAZ,ReadReplicaSourceDBInstanceIdentifier]"What you should see: a Multi-AZ primary and its replica:
[["shop3t-mysql", true, null], ["shop3t-mysql-replica", false, "shop3t-mysql"]]
Clean up: destroy everything
Delete everything this lab created. Type
yeswhen asked:terraform destroy -var my_ip_cidr=<your-ip>/32What you should see:
Destroy complete! Resources: 62 destroyed.Check the console the same day: no NAT gateways, load balancers, RDS instances or Elastic IPs from
shop3tshould remain.
Ravindra Bagale's Tip
Multi-AZ RDS (the standby) is for surviving a zone failure; the read replica is for spreading read traffic. They solve different problems, and interviewers love asking about the difference.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
Error: Invalid value for variable for my_ip_cidr | Plan stops at the variable check | The validation stopped an SSH rule open to the world. Find your IP with curl -s https://checkip.amazonaws.com and pass it with /32. |
SSH to the bastion: Permission denied (publickey) or a timeout | Cannot reach app servers | Permission denied: wrong key, or the key file is too open; run chmod 400 ~/.ssh/shop3t and ssh-add it. Timed out: your IP changed; update my_ip_cidr and apply again. |
Automated backups are not enabled when creating the replica | Read replica fails to create | Set backup_retention_period to 1 or more on the primary, apply, then create the replica. |
| Forgetting to destroy | NAT, ALB and RDS costs keep running | Run Clean up with the same -var the same day |
Self-check checklist
0 of 6 done
Try-at-home challenge
Optional (a few minutes of extra cost): run aws rds reboot-db-instance --db-instance-identifier shop3t-mysql --force-failover, then run the describe command again and see the primary move to the other zone while the endpoint name stays the same.
Samajla ka? Two zones for every tier, one way in for admins, one destroy at the end. Ha production cha aakaar aahe.