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
- Lab: Variables, Locals and for_each: One Config per Environment
An AWS account and the AWS CLI v2
The Session Manager plugin for the AWS CLI (optional, for step 14)
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 subnet10.0.1.0/24is public because its route table sends0.0.0.0/0to 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 fromuser_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.
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
Steps
-
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-identityCheck:get-caller-identityprints your account ID and an assumed-role ARN — not:root. -
2Pin the AWS provider
versions.tf terraform { required_version = ">= 1.6" required_providers { aws = { source = "hashicorp/aws" version = "~> 6.0" } } } -
3Region and default tags
default_tagsputs 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" } } } -
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." } } -
5The network
A VPC is your private network. The public subnet gets a route to the internet gateway;
cidrsubnetcarves10.0.1.0/24out 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 } -
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 } -
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_datainstalls 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 } } -
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 } -
9Initialise
Run terraform initExpected 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!
-
10Format and validate
Run terraform fmt -check terraform validateExpected output
Success! The configuration is valid.
-
11Plan
Terraform first reads the data sources (zones, AMI), then plans every resource.
Run terraform plan -out=tfplanCheck:Plan: 12 to add, 0 to change, 0 to destroy.The instance showshttp_tokens = "required"andencrypted = true, andurlis(known after apply). -
12Apply the saved plan
Applying the saved plan file runs exactly what you reviewed — the habit CI pipelines rely on.
Run terraform apply tfplanCheck:Apply complete! Resources: 12 addedand anurloutput such ashttp://ec2-...compute-1.amazonaws.com. -
13Open the page
The request reaches the internet gateway, which translates the instance's public IP to its private
10.0.1.xaddress. The security group checks port 80 againstallowed_http_cidr, and nginx answers. The reply leaves through the subnet's route0.0.0.0/0 → IGW.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,curlreports a refused connection — wait and retry. -
14Get a shell without SSH
Run aws ssm start-session --target $(terraform output -raw instance_id)Check:You get a shell as
ssm-user. Typeexitto 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.
-
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
Learn the concepts
- Terraform Providers · Terraform Tutorial
- Terraform Data Sources · Terraform Tutorial
- Terraform Resources · Terraform Tutorial
- Terraform Functions · Terraform Tutorial
- Terraform on AWS: Nonprod and Production Environments · Course
- Terraform in Production · Course
Preparing for the Terraform Associate exam? Practice tests and mock exams →