Terraform Labs · Lab 5 of 9

AWS: A Web Server in Its Own VPC

Build a small but properly structured AWS network — VPC, public subnet, internet gateway, route table and security group — and an EC2 web server with encrypted disk, IMDSv2, no SSH port and Session Manager access.

Environment
AWS
Level
Intermediate
Time
About 60 min
Cost
Free tier (t3.micro), otherwise ≈ $0.02 per hour

You will build

A public web page served from your own VPC, built from files split by concern (network, security, compute) the way real AWS projects are organised.

Before you start

Members can save this page, take notes and track progress. See membership · Sign in

This is your first lab that creates real cloud resources. Read every plan before typing yes, and finish with the clean-up section so nothing keeps costing money.

The plan and apply steps below say what to look for instead of showing output: AWS returns IDs and addresses that are different for every account.

What you will build

  • Region and AZ: everything sits in us-east-1, in one availability zone.
  • VPC 10.0.0.0/16: your private network. The public subnet 10.0.1.0/24 is public because its route table sends 0.0.0.0/0 to the internet gateway (IGW).
  • Security group: a stateful firewall around the instance: port 80 in from allowed_http_cidr, everything out.
  • EC2 t3.micro: runs nginx from user_data, with an encrypted gp3 disk and IMDSv2 required.
  • SSM Session Manager and the instance profile: the instance's IAM role lets the SSM agent connect out to AWS, so you get a shell without opening SSH.
InternetusersRegion us-east-1VPC 10.0.0.0/16IGWgatewayHTTPAZ us-east-1aPublic subnet 10.0.1.0/24Security group: tcp/80 in, all outEC2 t3.micronginx · encrypted gp3 · IMDSv2 onlyRoute table0.0.0.0/0 → IGWSSMagent connects outInstance profileIAM role + SSM policyNo SSH port open:shell access goesthrough SSM and IAM
What the AWS lab builds: a VPC with one public subnet, a locked-down EC2 web server and SSM access

Project structure

aws-web/
├── .gitignore
├── versions.tf    # Terraform and AWS provider versions
├── providers.tf   # region and default tags
├── variables.tf
├── network.tf     # VPC, subnet, internet gateway, routes
├── security.tf    # security group, IAM role for Session Manager
├── compute.tf     # EC2 instance
└── outputs.tf

Download starter filesDownload finished project

Steps

  1. 1Sign in to AWS without long-lived keys

    Use IAM Identity Center (SSO) or another short-lived login, never the root user and never access keys saved in files. Terraform's AWS provider reads the same credentials as the AWS CLI.

    Run
    aws configure sso          # once: creates a profile, e.g. lab
    aws sso login --profile lab
    export AWS_PROFILE=lab
    aws sts get-caller-identity
    
    Check:

    get-caller-identity prints your account ID and an assumed-role ARN — not :root.

  2. 2Pin the AWS provider

    versions.tf
    terraform {
      required_version = ">= 1.6"
    
      required_providers {
        aws = {
          source  = "hashicorp/aws"
          version = "~> 6.0"
        }
      }
    }
    
  3. 3Region and default tags

    default_tags puts the same tags on every resource, so cost reports can group by project and environment.

    providers.tf
    provider "aws" {
      region = var.region
    
      # Applied to every resource this configuration creates
      default_tags {
        tags = {
          Project     = var.project
          Environment = var.environment
          ManagedBy   = "terraform"
        }
      }
    }
    
  4. 4Inputs

    variables.tf
    variable "region" {
      description = "AWS region"
      type        = string
      default     = "us-east-1"
    }
    
    variable "project" {
      description = "Project name, used in resource names and tags"
      type        = string
      default     = "shop"
    }
    
    variable "environment" {
      description = "dev, staging or prod"
      type        = string
      default     = "dev"
    }
    
    variable "instance_type" {
      description = "EC2 instance type"
      type        = string
      default     = "t3.micro"
    }
    
    variable "allowed_http_cidr" {
      description = "Who may open the web page. Use your own IP with /32 to keep it private."
      type        = string
      default     = "0.0.0.0/0"
    
      validation {
        condition     = can(cidrhost(var.allowed_http_cidr, 0))
        error_message = "allowed_http_cidr must be a valid IPv4 CIDR block, e.g. 203.0.113.10/32."
      }
    }
    
  5. 5The network

    A VPC is your private network. The public subnet gets a route to the internet gateway; cidrsubnet carves 10.0.1.0/24 out of the VPC's range, and the availability zone comes from a data source instead of being hard-coded.

    network.tf
    data "aws_availability_zones" "available" {
      state = "available"
    }
    
    resource "aws_vpc" "main" {
      cidr_block           = "10.0.0.0/16"
      enable_dns_support   = true
      enable_dns_hostnames = true
    
      tags = { Name = "${var.project}-${var.environment}" }
    }
    
    resource "aws_subnet" "public" {
      vpc_id                  = aws_vpc.main.id
      cidr_block              = cidrsubnet(aws_vpc.main.cidr_block, 8, 1) # 10.0.1.0/24
      availability_zone       = data.aws_availability_zones.available.names[0]
      map_public_ip_on_launch = true
    
      tags = { Name = "${var.project}-${var.environment}-public" }
    }
    
    resource "aws_internet_gateway" "main" {
      vpc_id = aws_vpc.main.id
    
      tags = { Name = "${var.project}-${var.environment}" }
    }
    
    resource "aws_route_table" "public" {
      vpc_id = aws_vpc.main.id
    
      route {
        cidr_block = "0.0.0.0/0"
        gateway_id = aws_internet_gateway.main.id
      }
    
      tags = { Name = "${var.project}-${var.environment}-public" }
    }
    
    resource "aws_route_table_association" "public" {
      subnet_id      = aws_subnet.public.id
      route_table_id = aws_route_table.public.id
    }
    
  6. 6Security group and instance role

    Only port 80 is open. There is no SSH rule: the instance role allows AWS Systems Manager Session Manager, which gives you a shell through the AWS API with IAM permissions and an audit log.

    security.tf
    resource "aws_security_group" "web" {
      name        = "${var.project}-${var.environment}-web"
      description = "HTTP in, all out"
      vpc_id      = aws_vpc.main.id
    }
    
    resource "aws_vpc_security_group_ingress_rule" "http" {
      security_group_id = aws_security_group.web.id
      description       = "HTTP"
      cidr_ipv4         = var.allowed_http_cidr
      from_port         = 80
      to_port           = 80
      ip_protocol       = "tcp"
    }
    
    resource "aws_vpc_security_group_egress_rule" "all" {
      security_group_id = aws_security_group.web.id
      description       = "Package downloads and updates"
      cidr_ipv4         = "0.0.0.0/0"
      ip_protocol       = "-1"
    }
    
    # No SSH port: connect with Session Manager (aws ssm start-session) through this role instead.
    data "aws_iam_policy_document" "ec2_assume" {
      statement {
        actions = ["sts:AssumeRole"]
        principals {
          type        = "Service"
          identifiers = ["ec2.amazonaws.com"]
        }
      }
    }
    
    resource "aws_iam_role" "web" {
      name               = "${var.project}-${var.environment}-web"
      assume_role_policy = data.aws_iam_policy_document.ec2_assume.json
    }
    
    resource "aws_iam_role_policy_attachment" "ssm" {
      role       = aws_iam_role.web.name
      policy_arn = "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore"
    }
    
    resource "aws_iam_instance_profile" "web" {
      name = "${var.project}-${var.environment}-web"
      role = aws_iam_role.web.name
    }
    
  7. 7The web server

    The AMI comes from the public SSM parameter AWS keeps up to date. IMDSv2 is required, the root disk is encrypted, and user_data installs nginx on first boot.

    compute.tf
    # The latest Amazon Linux 2023 image, published by AWS as a public SSM parameter
    data "aws_ssm_parameter" "al2023" {
      name = "/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64"
    }
    
    resource "aws_instance" "web" {
      ami                    = data.aws_ssm_parameter.al2023.value
      instance_type          = var.instance_type
      subnet_id              = aws_subnet.public.id
      vpc_security_group_ids = [aws_security_group.web.id]
      iam_instance_profile   = aws_iam_instance_profile.web.name
    
      user_data = <<-EOT
        #!/bin/bash
        dnf install -y nginx
        echo "<h1>${var.project} ${var.environment}</h1><p>Served by $(hostname -f)</p>" > /usr/share/nginx/html/index.html
        systemctl enable --now nginx
      EOT
    
      user_data_replace_on_change = true
    
      metadata_options {
        http_tokens = "required" # IMDSv2 only
      }
    
      root_block_device {
        volume_size = 8
        volume_type = "gp3"
        encrypted   = true
      }
    
      tags = { Name = "${var.project}-${var.environment}-web" }
    
      lifecycle {
        ignore_changes = [ami] # a new AMI shouldn't replace the server on every plan; roll it out on purpose
      }
    }
    
  8. 8Outputs

    outputs.tf
    output "url" {
      description = "Open this in a browser (allow a minute or two for nginx to install)"
      value       = "http://${aws_instance.web.public_dns}"
    }
    
    output "instance_id" {
      description = "Use with: aws ssm start-session --target <id>"
      value       = aws_instance.web.id
    }
    
  9. 9Initialise

    Run
    terraform init
    

    Expected output

    Initializing provider plugins...
    - Finding hashicorp/aws versions matching "~> 6.0"...
    - Installing hashicorp/aws v6.74.0...
    - Installed hashicorp/aws v6.74.0 (signed by HashiCorp)
    ...
    Terraform has been successfully initialized!
  10. 10Format and validate

    Run
    terraform fmt -check
    terraform validate
    

    Expected output

    Success! The configuration is valid.
  11. 11Plan

    Terraform first reads the data sources (zones, AMI), then plans every resource.

    Run
    terraform plan -out=tfplan
    
    Check:

    Plan: 12 to add, 0 to change, 0 to destroy. The instance shows http_tokens = "required" and encrypted = true, and url is (known after apply).

  12. 12Apply the saved plan

    Applying the saved plan file runs exactly what you reviewed — the habit CI pipelines rely on.

    Run
    terraform apply tfplan
    
    Check:

    Apply complete! Resources: 12 added and an url output such as http://ec2-...compute-1.amazonaws.com.

  13. 13Open the page

    The request reaches the internet gateway, which translates the instance's public IP to its private 10.0.1.x address. The security group checks port 80 against allowed_http_cidr, and nginx answers. The reply leaves through the subnet's route 0.0.0.0/0 → IGW.

    Browserhttp://<public_ip>Internet gatewaypublic IP → 10.0.1.xSecurity grouptcp/80 from your CIDR?EC2: nginxserves index.htmlresponse: subnet route 0.0.0.0/0 → IGWOne request, step by step
    Request path: the internet gateway translates the public IP, the security group decides, nginx answers
    Run
    curl $(terraform output -raw url)
    
    Check:

    After a minute or two you get <h1>shop dev</h1> and the instance's host name. Until nginx is installed, curl reports a refused connection — wait and retry.

  14. 14Get a shell without SSH

    Run
    aws ssm start-session --target $(terraform output -raw instance_id)
    
    Check:

    You get a shell as ssm-user. Type exit to leave. There is still no port 22 open.

    Hint

    If the instance isn't listed yet, wait a minute: the SSM agent registers after boot.

  15. 15Restrict the page to your IP

    Run
    terraform apply -var "allowed_http_cidr=$(curl -s https://checkip.amazonaws.com)/32"
    
    Check:

    The plan changes only aws_vpc_security_group_ingress_rule.http; the instance is untouched.

Clean up

Destroy everything as soon as you're done — the instance and its public IPv4 address cost money every hour outside the free tier.

terraform destroy

Check for Destroy complete! Resources: 12 destroyed. and that the EC2 console shows the instance as terminated.

In production

What changes

In this lab In production
One public subnet in one availability zone Public and private subnets in at least two zones (usually three), from a reviewed VPC module
The instance has a public IP Instances sit in private subnets behind an Application Load Balancer; only the load balancer is public
HTTP on port 80 HTTPS with an ACM certificate on the load balancer; HTTP redirects to HTTPS
One instance, set up by user_data An Auto Scaling group with a launch template and health checks, or containers on ECS/EKS; images baked with Packer
Local state, your SSO session Remote state, and CI with OIDC roles applies changes (later labs)
ignore_changes = [ami] A deliberate image rollout: new launch template version and an instance refresh

Security defaults worth keeping

  • No SSH from the internet. Session Manager gives audited access with IAM, no keys to rotate.
  • IMDSv2 required, so a server-side request forgery can't read instance credentials.
  • Encrypted volumes, ideally enforced account-wide with EBS encryption by default.
  • Least-privilege instance role: only the policies the server needs.

Production checklist

  • Network spans at least two availability zones with private subnets for servers
  • Only load balancers are internet-facing, with TLS
  • Security groups reference other security groups instead of wide CIDR ranges
  • No SSH port open; access through Session Manager
  • IMDSv2 required and volumes encrypted on every instance
  • Every resource tagged with Project, Environment, Owner and ManagedBy
  • Budgets and cost alerts set on the account

Last reviewed · By the ByteCamel team · How we write content

Was this page helpful?

Report a mistake