Skip to main content

Infrastructure as code · Intermediate · 20 min

Launch the Relay web server with OpenTofu, an instance profile and cloud-init

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · OpenTofu 1.13.10 · hashicorp/aws 6.74 · cloud-init 26.2

You will launch Relay's Ubuntu 26.04 web server in its public subnet with OpenTofu, built from a looked-up image, a validated cloud-init template, an IAM role that can only read the assets bucket, IMDSv2 and an encrypted disk, and end with its public URL as an output.

On this page

Parts 1 and 2 gave Relay an assets bucket and a network with nowhere to serve from. In this part you add the server itself: one EC2 instance in the public-a subnet, behind the web security group, that installs Nginx on first boot and serves Relay's status page.

Five decisions go into the code, and each one is a line you can review in a plan:

  • The image is looked up, not pasted. AMI IDs differ per Region and change whenever Canonical publishes a new build, so a data source finds the newest Ubuntu 26.04 image owned by Canonical's account.
  • The boot script is a template. templatefile() fills in the environment and Region, and you validate the result with cloud-init schema before any server sees it.
  • The server gets a role, not keys. An IAM role and instance profile let it read the assets bucket and nothing else. No access key is ever written to the machine.
  • IMDSv2 is required. The metadata service hands out the role's temporary credentials, so it only answers requests that carry a session token.
  • The root disk is encrypted.

By the end, ~/relay-demo has compute.tf, iam.tf and templates/web-user-data.yaml.tftpl, and tofu output web_url prints the address of the page.

Step 1 · Confirm where part 2 left off

Go to the project and check that the state and the code still agree before you add anything:

Bash
cd ~/relay-demo
tofu plan -var-file=dev.tfvars
tofu state list | grep -E 'aws_s3_bucket.assets|aws_subnet.this\["public-a"\]|aws_security_group.web'

This part refers to three things by name: aws_s3_bucket.assets from part 1, and aws_subnet.this["public-a"] and aws_security_group.web from part 2. If you named yours differently, use your names in the code below.

Check it worked

The plan prints No changes. Your infrastructure matches the configuration. and the grep prints three lines, one for each of the resources above. If the plan wants to change something, sort that out first, so the next plans show only what this part adds.

Step 2 · Find the current Ubuntu 26.04 image

Canonical publishes Ubuntu images from AWS account 099720109477. Filtering on that owner matters: anyone can publish a public image called "ubuntu", and the owner ID is how you know the image really comes from Canonical. Create compute.tf with the lookup:

Bash
cat > compute.tf <<'HCL'
# Newest Ubuntu 26.04 LTS (Resolute Raccoon) image for x86, from Canonical only.
data "aws_ami" "ubuntu" {
  most_recent = true
  owners      = ["099720109477"]

  filter {
    name   = "name"
    values = ["ubuntu/images/hvm-ssd-gp3/ubuntu-resolute-26.04-amd64-server-*"]
  }

  filter {
    name   = "architecture"
    values = ["x86_64"]
  }

  filter {
    name   = "virtualization-type"
    values = ["hvm"]
  }
}
HCL
cat >> outputs.tf <<'HCL'

output "web_ami_name" {
  description = "Name of the Ubuntu image the web server is built from."
  value       = data.aws_ami.ubuntu.name
}
HCL
tofu plan -var-file=dev.tfvars -no-color | grep -F 'ubuntu-resolute-26.04-amd64-server-'

The name pattern ends in a build date, and most_recent = true takes the newest match. The amd64 image only boots on x86 instance types such as t3.micro. For Arm (Graviton) types such as t4g.micro, change amd64 to arm64 and x86_64 to arm64.

Canonical also publishes the current image ID as an SSM parameter (/aws/service/canonical/ubuntu/server/resolute/stable/current/amd64/hvm/ebs-gp3/ami-id), which you could read with the aws_ssm_parameter data source instead. Either works. The name filter used here lets you see in the plan exactly which build you are getting.

Check it worked

The plan lists a change to outputs only, and the grep prints the line + web_ami_name = "ubuntu/images/hvm-ssd-gp3/ubuntu-resolute-26.04-amd64-server-<date>", where <date> is the newest build in your Region. No resources are added yet.

Step 3 · Write the cloud-init template and validate it

cloud-init runs on the instance's first boot and reads its instructions from the user data. Keep them in their own file, as a template, so OpenTofu can fill in values and you can read the file without picking through HCL:

Bash
mkdir -p templates
cat > templates/web-user-data.yaml.tftpl <<'YAML'
#cloud-config
package_update: true
packages:
  - nginx

write_files:
  - path: /var/www/html/index.html
    owner: root:root
    permissions: "0644"
    defer: true
    content: |
      <!doctype html>
      <html lang="en">
      <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title>${site_name} status</title>
      </head>
      <body>
      <h1>${site_name} status</h1>
      <p>All systems normal.</p>
      <p>Environment: ${environment}. Region: ${region}.</p>
      </body>
      </html>

runcmd:
  - [systemctl, enable, --now, nginx]
YAML

The first line, #cloud-config, is how cloud-init knows the file is configuration rather than a shell script. defer: true holds the page back until the final boot stage, after the Nginx package is installed, so the package cannot get in its way. On Ubuntu, installing Nginx also starts it; the runcmd line makes that explicit.

The page is a few hundred bytes with no fonts, scripts or images to fetch. A status page is most often opened when something is wrong, sometimes on a low-end Android phone with a prepaid bundle running low, so it should load on any connection.

Now render the template. Add a local value and an output for it to compute.tf and outputs.tf:

Bash
cat >> compute.tf <<'HCL'

locals {
  web_user_data = templatefile("${path.module}/templates/web-user-data.yaml.tftpl", {
    site_name   = "Relay"
    environment = var.environment
    region      = var.region
  })
}
HCL
cat >> outputs.tf <<'HCL'

output "web_user_data" {
  description = "The rendered cloud-init user data. It holds no secrets; keep it that way."
  value       = local.web_user_data
}
HCL

Every ${...} in the template must be a key in the map, or templatefile() fails at plan time. That is a useful guard, and it also means a literal ${ in the template, for example in a shell snippet under runcmd, has to be written $${.

Save a plan, take the rendered user data out of it, and check it against cloud-init's schema. cloud-init schema is part of cloud-init, which Ubuntu Server already has; the apt install adds it, and jq, if they are missing:

Bash
sudo apt update
sudo apt install -y cloud-init jq
tofu plan -var-file=dev.tfvars -out=tfplan
tofu show -json tfplan | jq -r '.planned_values.outputs.web_user_data.value' > rendered-user-data.yaml
cloud-init schema --config-file rendered-user-data.yaml
grep -F 'Environment: dev. Region: eu-west-1.' rendered-user-data.yaml

A mistake here, such as package: nginx instead of packages:, would otherwise only show up as a server that boots without Nginx, and you would find out by reading its console log. The schema check finds it in a second, on your own machine.

Check it worked

cloud-init schema reports the file as valid, with a line like Valid schema rendered-user-data.yaml, and the grep prints the line with your environment and Region filled in. If you change packages: to package: in the template and run the four commands again, the schema check fails and names the key.

Step 4 · Give the server a role that reads only the assets bucket

A program on the server that needs AWS (a script that copies Relay's assets down, say) should not hold access keys. Instead, the instance gets an IAM role. EC2 attaches it through an instance profile, and the metadata service hands short-lived credentials for it to software on the instance, renewing them automatically.

Create iam.tf:

Bash
cat > iam.tf <<'HCL'
# Who may take on the role: the EC2 service, on behalf of an instance.
data "aws_iam_policy_document" "web_assume" {
  statement {
    actions = ["sts:AssumeRole"]

    principals {
      type        = "Service"
      identifiers = ["ec2.amazonaws.com"]
    }
  }
}

# What the role may do: list and read the assets bucket. Nothing else.
data "aws_iam_policy_document" "web_read_assets" {
  statement {
    sid       = "ListAssets"
    actions   = ["s3:ListBucket"]
    resources = [aws_s3_bucket.assets.arn]
  }

  statement {
    sid       = "ReadAssets"
    actions   = ["s3:GetObject"]
    resources = ["${aws_s3_bucket.assets.arn}/*"]
  }
}

resource "aws_iam_role" "web" {
  name_prefix        = "${local.name_prefix}-web-"
  assume_role_policy = data.aws_iam_policy_document.web_assume.json
}

resource "aws_iam_role_policy" "web_read_assets" {
  name   = "read-assets"
  role   = aws_iam_role.web.id
  policy = data.aws_iam_policy_document.web_read_assets.json
}

resource "aws_iam_instance_profile" "web" {
  name_prefix = "${local.name_prefix}-web-"
  role        = aws_iam_role.web.name
}
HCL
tofu plan -var-file=dev.tfvars -no-color | grep -E 'aws_iam_(role|role_policy|instance_profile)\.[a-z_]+ will be created'

The two statements need different resources. s3:ListBucket acts on the bucket itself, so its resource is the bucket's ARN. s3:GetObject acts on objects, so its resource ends in /*. Mixing these up is the most common reason a "read the bucket" policy does not work. There is no s3:PutObject or s3:DeleteObject: if someone gets a shell on the server, they still cannot change or empty the bucket.

IAM names are global to the account, so dev and prod roles in the same account would clash. name_prefix lets AWS add a unique suffix, giving names such as relay-dev-web-20261126....

Check it worked

The grep prints three lines: aws_iam_role.web will be created, aws_iam_role_policy.web_read_assets will be created and aws_iam_instance_profile.web will be created. In the full plan, the role policy shows the assets bucket's real ARN, because part 1 already created the bucket.

Step 5 · Write the instance

Read this before you apply anything in this step. The instance, its disk and its public IPv4 address bill from the moment they exist. As of 26 November 2026, AWS's EC2 Free Tier page lists t3.micro, t3.small, t4g.micro and t4g.small among the eligible instance types (with gp3 among the eligible volume types). For accounts on the current Free Tier, usage is covered by a USD 100 sign-up credit plus up to USD 100 more you can earn, for six months from account creation or until the credits run out, whichever comes first. Accounts created under the older Free Tier have different rules; check yours in the Billing console. Anything outside the Free Tier, including a larger instance type, a second instance or an account past its six months, bills at normal rates. Public IPv4 addresses are billed by the hour (see the VPC pricing page). To list the free-tier types in your Region:

Bash
aws ec2 describe-instance-types --filters Name=free-tier-eligible,Values=true \
  --query "InstanceTypes[*].InstanceType" --output text

Add a variable for the size, so prod can differ from dev without editing code:

Bash
cat >> variables.tf <<'HCL'

variable "web_instance_type" {
  type        = string
  description = "EC2 instance type for the web server. Must be x86 to match the amd64 image."
  default     = "t3.micro"
}
HCL

Then append the instance and its outputs:

Bash
cat >> compute.tf <<'HCL'

resource "aws_instance" "web" {
  ami                         = data.aws_ami.ubuntu.id
  instance_type               = var.web_instance_type
  subnet_id                   = aws_subnet.this["public-a"].id
  vpc_security_group_ids      = [aws_security_group.web.id]
  associate_public_ip_address = true
  iam_instance_profile        = aws_iam_instance_profile.web.name

  user_data                   = local.web_user_data
  user_data_replace_on_change = true

  metadata_options {
    http_endpoint               = "enabled"
    http_tokens                 = "required"
    http_put_response_hop_limit = 1
  }

  root_block_device {
    volume_type = "gp3"
    volume_size = 10
    encrypted   = true
  }

  tags = {
    Name = "${local.name_prefix}-web"
  }

  lifecycle {
    ignore_changes = [ami]
  }
}
HCL
cat >> outputs.tf <<'HCL'

output "web_instance_id" {
  description = "ID of the web server instance."
  value       = aws_instance.web.id
}

output "web_url" {
  description = "Public URL of the Relay status page."
  value       = "http://${aws_instance.web.public_ip}"
}
HCL
tofu fmt
tofu validate

The settings worth reading twice:

  • http_tokens = "required" turns on IMDSv2 only. The metadata service at 169.254.169.254 is where the role's credentials come from. With IMDSv1, a bug that makes the server fetch a URL for an attacker could fetch those credentials too. IMDSv2 needs a token from a PUT request first, which such bugs usually cannot send, and a hop limit of 1 stops the token leaving the instance, for example into a container on it.
  • user_data_replace_on_change = true. cloud-init runs once, on first boot. Without this, editing the template would update the stored user data and change nothing on the running server. With it, a template change shows in the plan as a replacement, which is honest about what will happen.
  • ignore_changes = [ami]. The lookup finds a newer image whenever Canonical publishes one. Without this line, every new build would plan a replacement of the server. You pick up new images on purpose instead, by replacing the instance when you choose to.
  • encrypted = true encrypts the root volume with the account's default EBS key. You can also switch on EBS encryption by default for the whole Region, but the code says it either way.

The server has no SSH key pair. It does not need one in this part, and the page is the check. If you want to log in, add key_name with a key pair you created, as in launch an EC2 instance and connect.

Check it worked

tofu validate prints Success! The configuration is valid. tofu fmt lists any file it reformatted, or nothing.

Step 6 · Plan, review and apply

Save the plan and check the security settings in it with jq before you apply. jq -e exits with an error if the answer is false, so a wrong setting stops you here:

Bash
tofu plan -var-file=dev.tfvars -out=tfplan
tofu show -json tfplan | jq -e '.resource_changes[] | select(.address == "aws_instance.web") | .change.after | .metadata_options[0].http_tokens == "required" and .root_block_device[0].encrypted == true'
tofu show -json tfplan | jq -r '.resource_changes[] | select(.change.actions == ["create"]) | .address'

Apply exactly that plan. This is the point where billing starts:

Bash
tofu apply tfplan
tofu output web_url
tofu state show -no-color aws_instance.web | grep -E 'http_tokens|encrypted|iam_instance_profile'

Check it worked

The jq -e line prints true. The list of new addresses has four entries: aws_iam_instance_profile.web, aws_iam_role.web, aws_iam_role_policy.web_read_assets and aws_instance.web. The apply ends with Apply complete! Resources: 4 added, 0 changed, 0 destroyed., tofu output web_url prints something like "http://198.51.100.24", and the state shows http_tokens = "required", encrypted = true and the instance profile's name.

Step 7 · Load the status page

cloud-init needs a minute or two after the instance starts to update the package lists, install Nginx and write the page. Poll the address until it answers:

Bash
until curl -fsS --max-time 5 "$(tofu output -raw web_url)"; do sleep 10; done

If it never answers, read what cloud-init did. The console output includes its log, and it takes a few minutes after boot to appear:

Bash
aws ec2 get-console-output --instance-id "$(tofu output -raw web_instance_id)" --latest --output text | tail -n 40

The usual causes are a security group without port 80 (part 2), a subnet without a route to the internet gateway, or a user data mistake the schema check could not catch, such as a package name that does not exist.

This page is served over plain HTTP. Port 443 is open in the security group, but nothing listens on it yet.

If you pause the series for more than a day, you can remove only the server to stop its charges, and the next tofu apply -var-file=dev.tfvars builds it again from the same code. Keep the rest, which later parts need:

Bash
tofu destroy -var-file=dev.tfvars -target=aws_instance.web

-target is for exceptions like this one; read the destroy plan, which should list one resource, before you type yes.

Check it worked

The curl loop ends by printing the page's HTML, including <h1>Relay status</h1> and Environment: dev. Region: eu-west-1. with your Region. Opening the web_url address in a browser shows the same page.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.