Ravindra BagaleCourses & study guides Track your progress

Labs · DevOps

Lab: Build a Single-AZ 3-Tier Stack with Terraform: Public Web Server, Private App Server, NAT Gateway and a Private RDS Database

Advanced90 minTerraform 1.6+ · AWS CLI v2 · An AWS account

Course: DevOps · Chapter 45: Terraform 3-Tier Architecture in a Single Availability Zone · Lesson: 45.1 The single-AZ 3-tier design, file layout and network

Chapter 45 explains each file in five lessons; this lab is the step-by-step run sheet for the whole stack.

Chala mitrano! Web, app, database: teen thar, ek zone. Aaj poorna stack banvuya, test karuya ani destroy karuya.

Suppose we are…

Suppose we are on an Infosys client team building a first internal HR portal for 200 staff. They want the classic three layers: a web server that users reach, an app server hidden in a private subnet, and a database in its own subnet. To keep it simple and cheap for a pilot, everything runs in one Availability Zone. This chapter builds that layout; the next chapter makes it survive a zone failure.

Goal of this lab

By the end you will have:

  • A VPC with a public subnet, a private app subnet and DB subnets, plus a NAT gateway.
  • A web page and an /api/ answer from the private app server.
  • A private, single-AZ RDS database, and the whole stack destroyed.

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-identity works). Never use the root user, and never paste access keys into .tf files.
  • Region Mumbai (ap-south-1) is used; change region if you prefer another.
  • 90 minutes (RDS creation takes the longest).

Cost and cleanup

A NAT gateway and RDS are billed every hour they exist, even with no traffic. 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: Network

  1. Create the folder:

    mkdir three-tier-single-az && cd three-tier-single-az
    

    What you should see: at the end of Part 4 you will have:

    three-tier-single-az/
    ├── versions.tf
    ├── variables.tf
    ├── network.tf
    ├── security.tf
    ├── compute.tf
    ├── db.tf
    └── outputs.tf
    
  2. Create versions.tf:

    versions.tf

    terraform {
      required_version = ">= 1.6"
      required_providers {
        aws = {
          source  = "hashicorp/aws"
          version = "~> 5.0"
        }
      }
    }
    
    provider "aws" {
      region = var.region
    }
    
  3. Create variables.tf:

    variables.tf

    variable "region" {
      type    = string
      default = "ap-south-1"
    }
    
    variable "project" {
      type    = string
      default = "tier1az"
    }
    
    variable "instance_type" {
      type    = string
      default = "t3.micro"
    }
    
    variable "db_username" {
      type    = string
      default = "appadmin"
    }
    
  4. Create network.tf:

    network.tf

    data "aws_availability_zones" "available" {
      state = "available"
    }
    
    locals {
      az_a = data.aws_availability_zones.available.names[0]
      az_b = data.aws_availability_zones.available.names[1]
    }
    
    resource "aws_vpc" "main" {
      cidr_block           = "10.30.0.0/16"
      enable_dns_support   = true
      enable_dns_hostnames = true
      tags = {
        Name = "${var.project}-vpc"
      }
    }
    
    resource "aws_internet_gateway" "igw" {
      vpc_id = aws_vpc.main.id
    }
    
    resource "aws_subnet" "public" {
      vpc_id                  = aws_vpc.main.id
      cidr_block              = "10.30.1.0/24"
      availability_zone       = local.az_a
      map_public_ip_on_launch = true
      tags = {
        Name = "${var.project}-public-a"
      }
    }
    
    resource "aws_subnet" "app" {
      vpc_id            = aws_vpc.main.id
      cidr_block        = "10.30.11.0/24"
      availability_zone = local.az_a
      tags = {
        Name = "${var.project}-app-a"
      }
    }
    
    resource "aws_subnet" "db_a" {
      vpc_id            = aws_vpc.main.id
      cidr_block        = "10.30.21.0/24"
      availability_zone = local.az_a
      tags = {
        Name = "${var.project}-db-a"
      }
    }
    
    resource "aws_subnet" "db_b" {
      vpc_id            = aws_vpc.main.id
      cidr_block        = "10.30.22.0/24"
      availability_zone = local.az_b
      tags = {
        Name = "${var.project}-db-b"
      }
    }
    
    resource "aws_eip" "nat" {
      domain = "vpc"
    }
    
    resource "aws_nat_gateway" "nat" {
      allocation_id = aws_eip.nat.id
      subnet_id     = aws_subnet.public.id
      depends_on    = [aws_internet_gateway.igw]
    }
    
    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" "private" {
      vpc_id = aws_vpc.main.id
      route {
        cidr_block     = "0.0.0.0/0"
        nat_gateway_id = aws_nat_gateway.nat.id
      }
    }
    
    resource "aws_route_table_association" "public" {
      subnet_id      = aws_subnet.public.id
      route_table_id = aws_route_table.public.id
    }
    
    resource "aws_route_table_association" "app" {
      subnet_id      = aws_subnet.app.id
      route_table_id = aws_route_table.private.id
    }
    
  5. Init and review only the network:

    terraform init
    terraform validate
    terraform plan -target=aws_route_table_association.app
    

    What you should see: the network resources only:

    $ terraform plan -target=aws_route_table_association.app
    Plan: 12 to add, 0 to change, 0 to destroy.
    

Part 2: Security groups

  1. Create security.tf:

    security.tf

    resource "aws_security_group" "web" {
      name   = "${var.project}-web"
      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_vpc_security_group_ingress_rule" "web_http" {
      security_group_id = aws_security_group.web.id
      cidr_ipv4         = "0.0.0.0/0"
      ip_protocol       = "tcp"
      from_port         = 80
      to_port           = 80
    }
    
    resource "aws_vpc_security_group_ingress_rule" "app_from_web" {
      security_group_id            = aws_security_group.app.id
      referenced_security_group_id = aws_security_group.web.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_egress_rule" "web_all" {
      security_group_id = aws_security_group.web.id
      cidr_ipv4         = "0.0.0.0/0"
      ip_protocol       = "-1"
    }
    
    resource "aws_vpc_security_group_egress_rule" "app_all" {
      security_group_id = aws_security_group.app.id
      cidr_ipv4         = "0.0.0.0/0"
      ip_protocol       = "-1"
    }
    
  2. Validate and check the rules:

    terraform validate
    grep -n "0.0.0.0/0" security.tf
    

    What you should see: 0.0.0.0/0 only on the web HTTP ingress and on egress rules.

Part 3: Web and app servers

  1. Create compute.tf:

    compute.tf

    data "aws_ami" "al2023" {
      most_recent = true
      owners      = ["amazon"]
      filter {
        name   = "name"
        values = ["al2023-ami-2023.*-x86_64"]
      }
    }
    
    resource "aws_instance" "app" {
      ami                    = data.aws_ami.al2023.id
      instance_type          = var.instance_type
      subnet_id              = aws_subnet.app.id
      vpc_security_group_ids = [aws_security_group.app.id]
      metadata_options {
        http_tokens = "required"
      }
      user_data = <<-EOT
        #!/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 app
      EOT
      tags = {
        Name = "${var.project}-app"
      }
    }
    
    resource "aws_instance" "web" {
      ami                    = data.aws_ami.al2023.id
      instance_type          = var.instance_type
      subnet_id              = aws_subnet.public.id
      vpc_security_group_ids = [aws_security_group.web.id]
      metadata_options {
        http_tokens = "required"
      }
      user_data = <<-EOT
        #!/bin/bash
        dnf install -y nginx
        echo "web tier ok" > /usr/share/nginx/html/index.html
        cat > /etc/nginx/default.d/app.conf <<'CONF'
        location /api/ {
          proxy_pass http://${aws_instance.app.private_ip}:8080/;
        }
        CONF
        systemctl enable --now nginx
      EOT
      tags = {
        Name = "${var.project}-web"
      }
    }
    
  2. Validate:

    terraform validate
    

Part 4: Database and outputs

  1. Create db.tf:

    db.tf

    resource "aws_db_subnet_group" "db" {
      name       = "${var.project}-db"
      subnet_ids = [aws_subnet.db_a.id, aws_subnet.db_b.id]
    }
    
    resource "aws_db_instance" "main" {
      identifier                  = "${var.project}-mysql"
      engine                      = "mysql"
      engine_version              = "8.0"
      instance_class              = "db.t3.micro"
      allocated_storage           = 20
      storage_type                = "gp3"
      storage_encrypted           = true
      db_name                     = "appdb"
      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]
      availability_zone           = local.az_a
      multi_az                    = false
      publicly_accessible         = false
      backup_retention_period     = 7
      skip_final_snapshot         = true
    }
    
  2. Create outputs.tf:

    outputs.tf

    output "web_url" {
      value = "http://${aws_instance.web.public_ip}"
    }
    
    output "app_private_ip" {
      value = aws_instance.app.private_ip
    }
    
    output "db_endpoint" {
      value = aws_db_instance.main.endpoint
    }
    
  3. Validate and read the total:

    terraform validate
    terraform plan
    

    What you should see: 24 resources to add.

Part 5: Apply and test

  1. Save the plan and apply exactly that plan:

    terraform fmt -recursive
    terraform plan -out tfplan
    terraform apply tfplan
    
  2. Wait 3 minutes for user_data, then test each tier:

    curl -s $(terraform output -raw web_url)
    curl -s $(terraform output -raw web_url)/api/
    aws rds describe-db-instances --db-instance-identifier tier1az-mysql --query "DBInstances[0].[PubliclyAccessible,MultiAZ,AvailabilityZone]"
    

    What you should see: the web tier, the app tier answering through nginx, and RDS private in one zone:

    web tier ok
    app tier: ip-10-30-11-25.ap-south-1.compute.internal
    [ false, false, "ap-south-1a" ]
    

Clean up: destroy everything

  1. Delete everything this lab created. Type yes when asked:

    terraform destroy
    

    What you should see: Destroy complete! Resources: 24 destroyed.

  2. Check the console for leftovers: VPC → NAT gateways and Elastic IPs should show nothing from this lab.

Ravindra Bagale's Tip

Single-AZ is fine for a pilot, never for production. If that zone has a problem, the whole stack is down. The next lab fixes exactly that.

Common mistakes

MistakeWhat happensFix
Error: creating EC2 NAT Gateway: InvalidSubnetID.NotFoundNetwork apply failsUse the data source for zone names instead of typing them, and make sure the NAT references aws_subnet.public.id. Check you are in the region set in variables.tf.
Error: deleting EC2 Internet Gateway: DependencyViolation:Destroy stopsUsually a resource created outside Terraform (for example a console test instance) is still in the VPC. Delete it, then run terraform destroy again.
Forgetting to destroyNAT and RDS bill every hourRun the Clean up part the same day

Self-check checklist

0 of 5 done

Try-at-home challenge

Add an IAM role with AmazonSSMManagedInstanceCore to both servers and connect to the app server with Session Manager.

Samajla ka? Three tiers, one zone, one destroy. Aata pudhe jaauya multi-AZ.