Ravindra BagaleCourses & study guides Track your progress

Labs · DevOps

Lab: Build Your Own VPC with Two Public Subnets, an EC2 nginx Server Using an IAM Role (No Keys, No SSH), and a Private S3 Bucket It Can Read

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

Course: DevOps · Chapter 40: Terraform Real AWS Labs VPC EC2 nginx S3 and IAM Role · Lesson: 40.1 Lab part 1: VPC, public subnets, internet gateway

Chapter 40 builds this in five parts with every line explained; this lab is the one-page run sheet.

Chala mitrano! Default VPC sodun aaj aapla swatahacha network. Ani server la keys nahit, SSH nahi, fakt role.

Suppose we are…

An Instagram-style feature team wanted a fresh, isolated network for a load-test week, built the same way every time and deleted afterwards. A VPC needs subnets, an internet gateway and a route table before any server can reach the internet. Writing it yourself once teaches what the registry VPC module hides. The deep VPC theory stays in the AWS course; here we build the minimum in code.

Goal of this lab

By the end you will have:

  • A VPC with two public subnets in two zones, an internet gateway and a route table.
  • An nginx page reachable in the browser, from a server with no SSH port.
  • The server reading a private S3 object through its IAM role, then everything 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.
  • 60 minutes.

Cost and cleanup

One t3.micro instance and a small bucket. 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: Files

  1. Create the folder and versions.tf:

    versions.tf

    terraform {
      required_version = ">= 1.6"
      required_providers {
        aws = {
          source  = "hashicorp/aws"
          version = "~> 5.0"
        }
      }
    }
    
    provider "aws" {
      region = "ap-south-1"
    }
    
    mkdir vpc-lab && cd vpc-lab
    
  2. Network (lesson 40.1):

    vpc.tf

    data "aws_availability_zones" "available" {
      state = "available"
    }
    
    resource "aws_vpc" "lab" {
      cidr_block           = "10.20.0.0/16"
      enable_dns_hostnames = true
      tags                 = { Name = "badge-lab-vpc" }
    }
    
    resource "aws_subnet" "public" {
      for_each                = { a = 0, b = 1 }
      vpc_id                  = aws_vpc.lab.id
      cidr_block              = cidrsubnet(aws_vpc.lab.cidr_block, 8, each.value + 1)
      availability_zone       = data.aws_availability_zones.available.names[each.value]
      map_public_ip_on_launch = true
      tags                    = { Name = "badge-lab-public-${each.key}" }
    }
    
    resource "aws_internet_gateway" "lab" {
      vpc_id = aws_vpc.lab.id
    }
    
    resource "aws_route_table" "public" {
      vpc_id = aws_vpc.lab.id
      route {
        cidr_block = "0.0.0.0/0"
        gateway_id = aws_internet_gateway.lab.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
    }
    
  3. Web security group: HTTP in, all out, no SSH (lesson 40.2):

    sg.tf

    resource "aws_security_group" "web" {
      name        = "badge-lab-web"
      description = "HTTP in, all out"
      vpc_id      = aws_vpc.lab.id
    }
    
    resource "aws_vpc_security_group_ingress_rule" "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_egress_rule" "all" {
      security_group_id = aws_security_group.web.id
      cidr_ipv4         = "0.0.0.0/0"
      ip_protocol       = "-1"
    }
    
  4. The server with nginx from user_data and IMDSv2 (lesson 40.3):

    ec2.tf

    data "aws_ami" "al2023" {
      most_recent = true
      owners      = ["amazon"]
      filter {
        name   = "name"
        values = ["al2023-ami-2023.*-x86_64"]
      }
    }
    
    resource "aws_instance" "web" {
      ami                    = data.aws_ami.al2023.id
      instance_type          = "t3.micro"
      subnet_id              = aws_subnet.public["a"].id
      vpc_security_group_ids = [aws_security_group.web.id]
      iam_instance_profile   = aws_iam_instance_profile.web.name
    
      metadata_options {
        http_tokens = "required"
      }
    
      user_data = <<-EOF
        #!/bin/bash
        dnf install -y nginx
        TOKEN=$(curl -s -X PUT http://169.254.169.254/latest/api/token -H "X-aws-ec2-metadata-token-ttl-seconds: 60")
        ID=$(curl -s -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/instance-id)
        echo "<h1>Badge lab - $ID</h1>" > /usr/share/nginx/html/index.html
        systemctl enable --now nginx
      EOF
    
      user_data_replace_on_change = true
      tags = { Name = "badge-lab-web" }
    }
    
    output "web_url" {
      value = "http://${aws_instance.web.public_dns}"
    }
    
  5. IAM role with Session Manager and read access to one bucket (lesson 40.4):

    iam.tf

    data "aws_iam_policy_document" "ec2_trust" {
      statement {
        actions = ["sts:AssumeRole"]
        principals {
          type        = "Service"
          identifiers = ["ec2.amazonaws.com"]
        }
      }
    }
    
    resource "aws_iam_role" "web" {
      name               = "badge-lab-web-role"
      assume_role_policy = data.aws_iam_policy_document.ec2_trust.json
    }
    
    resource "aws_iam_role_policy_attachment" "ssm" {
      role       = aws_iam_role.web.name
      policy_arn = "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore"
    }
    
    data "aws_iam_policy_document" "read_assets" {
      statement {
        actions   = ["s3:GetObject"]
        resources = ["${aws_s3_bucket.assets.arn}/*"]
      }
    }
    
    resource "aws_iam_role_policy" "read_assets" {
      role   = aws_iam_role.web.id
      policy = data.aws_iam_policy_document.read_assets.json
    }
    
    resource "aws_iam_instance_profile" "web" {
      name = "badge-lab-web-profile"
      role = aws_iam_role.web.name
    }
    
  6. The private bucket and a test object (lesson 40.5). Replace <your-account-id>:

    s3.tf

    resource "aws_s3_bucket" "assets" {
      bucket        = "badge-lab-assets-<your-account-id>"
      force_destroy = true
    }
    
    resource "aws_s3_bucket_public_access_block" "assets" {
      bucket                  = aws_s3_bucket.assets.id
      block_public_acls       = true
      block_public_policy     = true
      ignore_public_acls      = true
      restrict_public_buckets = true
    }
    
    resource "aws_s3_object" "hello" {
      bucket  = aws_s3_bucket.assets.id
      key     = "hello.txt"
      content = "served through the instance role"
    }
    

Part 2: Plan and apply

  1. Init, format, validate and plan:

    terraform init
    terraform fmt
    terraform validate
    terraform plan
    

    What you should see: about 18 resources to add.

  2. Apply, wait about two minutes for nginx, then open the page:

    terraform apply
    curl -s $(terraform output -raw web_url)
    

    What you should see: the page with your instance id:

    Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
    Outputs:
    web_url = "http://ec2-203-0-113-25.ap-south-1.compute.amazonaws.com"
    
    $ curl -s $(terraform output -raw web_url)
    <h1>Badge lab - i-0abc123...</h1>
    

Part 3: Read S3 through the role

  1. In the console open EC2 → Instances → badge-lab-web → Connect → Session Manager → Connect. In that browser shell run:

    aws s3 cp s3://badge-lab-assets-<your-account-id>/hello.txt -
    

    What you should see: served through the instance role. No keys were configured on the server.

Clean up: destroy everything

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

    terraform destroy
    

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

Ravindra Bagale's Tip

Write terraform destroy on a sticky note before you type apply.

Common mistakes

MistakeWhat happensFix
Error: creating EC2 Subnet: InvalidSubnet.Conflict:Subnet creation failsTwo subnets got the same range, usually from a wrong cidrsubnet number. Make the netnum unique per subnet.
AccessDenied reading hello.txtRole cannot read the objectThe role policy resource ARN is wrong, or the instance profile is missing. Check part 4 and remember the /* at the end of the bucket ARN.
Connection refused on port 80Page does not loadWait a minute for cloud-init, then check sudo cat /var/log/cloud-init-output.log through Session Manager. If the connection times out instead, the route table or security group is wrong.

Self-check checklist

0 of 5 done

Try-at-home challenge

Add a second instance in subnet b using for_each over the subnets, and describe the plan you expect.

Samajla ka? Network, server, role, bucket, destroy. Aata pudhe jaauya 3-tier.