Skip to main content

Infrastructure as code · Intermediate · 30 min

Build a reusable server image with Packer

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Packer 1.16.3 · amazon plugin 1.8.4 · ansible plugin 1.1.6 · Ansible 15.0.0 (ansible-core 2.22)

You will write a Packer 1.16 template that bakes Nginx, hardened with Ansible, into an Ubuntu 26.04 Amazon Machine Image, check it with packer init, fmt and validate, and know how to build it, record it in a manifest and delete it so it stops billing.

On this page

There are two ways to get a configured web server out of a blank Ubuntu instance. You can run the setup every time a server boots: user data that installs Nginx, writes its config and hopes the package mirror answers. Or you can run that setup once, save the result as a machine image, and start every server from the finished image.

Packer does the second. It starts a temporary instance from a base image, runs your provisioners on it, shuts it down and saves its disk as a new image. Baking wins in three ways:

  • Speed. A server from a baked image is ready when it boots. Nothing downloads, so autoscaling reacts in seconds, not minutes.
  • Sameness. Every server runs exactly the packages that were tested in the image, not whatever the mirror had that morning. A failed apt run during a traffic spike cannot leave you with half a server.
  • Rollback. Each image has a version. Going back means launching the previous one.

Boot-time configuration still has a job: per-server details such as a hostname or a secret fetched at start. The write-cloud-init-user-data-for-a-new-server tutorial covers that half.

You will build a template for an image called web-nginx: Ubuntu 26.04 from Canonical's official images, updated by a shell script, with Nginx installed and hardened by an Ansible playbook, cleaned up by a second script, and recorded in a manifest file. Everything lives in ~/packer-image-demo, a throwaway folder you delete at the end.

Step 1 · Install Packer and Ansible

Packer runs on the machine you start the build from, which is usually your laptop or a CI runner. The Ansible provisioner also runs ansible-playbook on that machine and connects to the temporary instance over SSH, so both tools go on the same machine.

Install the helpers first:

Bash
sudo apt-get update
sudo apt-get install -y curl unzip ca-certificates jq pipx openssh-client

Download the Packer 1.16.3 release for your CPU, check it against HashiCorp's published checksums and install it:

Bash
PACKER_VERSION=1.16.3
ARCH=$(dpkg --print-architecture)
cd "$(mktemp -d)"
curl -fsSLO "https://releases.hashicorp.com/packer/${PACKER_VERSION}/packer_${PACKER_VERSION}_linux_${ARCH}.zip"
curl -fsSLO "https://releases.hashicorp.com/packer/${PACKER_VERSION}/packer_${PACKER_VERSION}_SHA256SUMS"
sha256sum --ignore-missing -c "packer_${PACKER_VERSION}_SHA256SUMS"
unzip -o "packer_${PACKER_VERSION}_linux_${ARCH}.zip" packer
sudo install -m 0755 packer /usr/local/bin/packer
packer version

A binary installed this way gets no updates from apt. To upgrade, run the block again with a newer PACKER_VERSION from releases.hashicorp.com. On macOS, brew install hashicorp/tap/packer installs the same tool.

Install Ansible from PyPI with pipx, pinned so your output matches this page:

Bash
pipx install --include-deps ansible==15.0.0
export PATH="$HOME/.local/bin:$PATH"
ansible-playbook --version

Add the PATH line to ~/.bashrc (or run pipx ensurepath). Packer looks for ansible-playbook on your PATH, and a build fails early if it cannot find it.

Check it worked

sha256sum prints packer_1.16.3_linux_amd64.zip: OK (or arm64), packer version prints Packer v1.16.3, and the first line from ansible-playbook --version starts with ansible-playbook [core 2.22..

Step 2 · Pin the plugins and run packer init

Since Packer 1.10, the builders for each cloud are separate plugins. A packer block says which plugins the template needs and which versions it accepts, in the same way a Terraform required_providers block does. Create the project and that file:

Bash
mkdir -p ~/packer-image-demo/scripts ~/packer-image-demo/ansible
cd ~/packer-image-demo

cat > plugins.pkr.hcl <<'HCL'
packer {
  required_version = "~> 1.16"

  required_plugins {
    amazon = {
      source  = "github.com/hashicorp/amazon"
      version = "~> 1.8"
    }
    ansible = {
      source  = "github.com/hashicorp/ansible"
      version = "~> 1.1"
    }
  }
}
HCL

packer init .
packer plugins installed

~> 1.8 accepts any 1.x release from 1.8 upwards, so a bug-fix release arrives the next time you run packer init -upgrade ., and a 2.0 with breaking changes does not. Packer reads every *.pkr.hcl file in the folder as one template, so you can split the template across files the way you would a Terraform module.

Check it worked

packer init . reports something like Installed plugin github.com/hashicorp/amazon v1.8.4 and the same for github.com/hashicorp/ansible v1.1.6. packer plugins installed lists two binaries under ~/.config/packer/plugins/github.com/hashicorp/. Running packer init . a second time installs nothing.

Step 3 · Declare variables and the amazon-ebs source

Two values change between builds: the AWS Region and the version you stamp on the image. Make them variables, and refuse a version that does not look like 1.2.3:

Bash
cat > variables.pkr.hcl <<'HCL'
variable "region" {
  type        = string
  description = "AWS Region to build the image in."
  default     = "eu-west-2"
}

variable "instance_type" {
  type        = string
  description = "Instance type for the temporary build instance."
  default     = "t3.micro"
}

variable "image_version" {
  type        = string
  description = "Version stamped on the image, such as 1.0.0."

  validation {
    condition     = can(regex("^[0-9]+\\.[0-9]+\\.[0-9]+$", var.image_version))
    error_message = "The image_version must be three numbers separated by dots, such as 1.0.0."
  }
}

locals {
  build_time = formatdate("YYYYMMDD-hhmm", timestamp())
  image_name = "web-nginx-${var.image_version}-${local.build_time}"
}
HCL

image_version has no default, so every build has to say which version it is making. Image names must be unique in your account and Region; the timestamp in image_name lets you rebuild the same version without a clash.

If most of your users are in Southern Africa, af-south-1 (Cape Town) is the closer Region. It is an opt-in Region, so enable it in your AWS account settings before you pass -var region=af-south-1.

Now the source, which says where the build starts and what it produces:

Bash
cat > web.pkr.hcl <<'HCL'
source "amazon-ebs" "web" {
  region        = var.region
  instance_type = var.instance_type
  ssh_username  = "ubuntu"
  ami_name      = local.image_name
  imds_support  = "v2.0"

  source_ami_filter {
    filters = {
      name                = "ubuntu/images/hvm-ssd-gp3/ubuntu-resolute-26.04-amd64-server-*"
      root-device-type    = "ebs"
      virtualization-type = "hvm"
    }
    owners      = ["099720109477"]
    most_recent = true
  }

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

  temporary_security_group_source_public_ip = true

  run_tags = {
    Name = "packer-build-web"
  }

  tags = {
    Name         = local.image_name
    ImageVersion = var.image_version
    BaseOS       = "Ubuntu 26.04"
  }

  snapshot_tags = {
    Name         = local.image_name
    ImageVersion = var.image_version
  }
}
HCL

What each part does:

  • source_ami_filter finds the newest Ubuntu 26.04 server image. owners is Canonical's AWS account, so a look-alike image published by someone else can never match. resolute is the 26.04 release name in Canonical's image names.
  • metadata_options makes the build instance require IMDSv2 session tokens, and imds_support = "v2.0" sets the same rule on every server launched from the finished image.
  • temporary_security_group_source_public_ip opens SSH on the temporary instance to your own public IP only, not the whole internet.
  • run_tags names the temporary instance so you can find it if a build is cut short. tags and snapshot_tags label the image and the disk snapshot behind it.

Check it worked

ls ~/packer-image-demo shows plugins.pkr.hcl, variables.pkr.hcl, web.pkr.hcl and the two empty folders. Nothing has been sent to AWS: a source only describes a build until a build block uses it.

Step 4 · Write the provisioner scripts and the Nginx playbook

Three provisioners will run on the temporary instance, in order. First a shell script that waits for the instance's own first-boot setup to finish, applies updates and installs the packages Ansible and automatic security updates need:

Bash
cat > scripts/base.sh <<'SH'
#!/bin/sh
set -eu

# On a fresh instance, cloud-init may still be running apt. Wait for it.
# Exit code 2 means it finished with warnings, which is fine here.
if command -v cloud-init >/dev/null 2>&1; then
  cloud-init status --wait || true
fi

apt-get update
apt-get -y -o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold upgrade
apt-get install -y python3 unattended-upgrades
SH

Then the playbook. It installs Nginx, hides the Nginx version from response headers, adds security headers, replaces the default site with one for this image and writes the image version where you can read it later:

Bash
cat > ansible/nginx.yml <<'YAML'
- name: Install and harden Nginx for the web image
  hosts: all
  become: true
  vars:
    image_version: "0.0.0"

  tasks:
    - name: Install Nginx
      ansible.builtin.apt:
        name: nginx
        state: present
        update_cache: true

    - name: Hide the Nginx version in headers and error pages
      ansible.builtin.lineinfile:
        path: /etc/nginx/nginx.conf
        regexp: '^\s*#?\s*server_tokens\s'
        line: "\tserver_tokens off;"
        insertafter: '^http \{'

    - name: Add security headers for every site
      ansible.builtin.copy:
        dest: /etc/nginx/conf.d/hardening.conf
        mode: "0644"
        content: |
          client_max_body_size 1m;
          add_header X-Content-Type-Options "nosniff" always;
          add_header X-Frame-Options "DENY" always;
          add_header Referrer-Policy "strict-origin-when-cross-origin" always;

    - name: Remove the default site
      ansible.builtin.file:
        path: /etc/nginx/sites-enabled/default
        state: absent

    - name: Add the site for this image
      ansible.builtin.copy:
        dest: /etc/nginx/sites-available/web.conf
        mode: "0644"
        content: |
          server {
              listen 80 default_server;
              listen [::]:80 default_server;
              root /var/www/web;
              index index.html;
              location / {
                  try_files $uri $uri/ =404;
              }
          }

    - name: Enable the site
      ansible.builtin.file:
        src: /etc/nginx/sites-available/web.conf
        dest: /etc/nginx/sites-enabled/web.conf
        state: link

    - name: Create the web root
      ansible.builtin.file:
        path: /var/www/web
        state: directory
        mode: "0755"

    - name: Write the home page
      ansible.builtin.copy:
        dest: /var/www/web/index.html
        mode: "0644"
        content: |
          <!doctype html>
          <title>web-nginx</title>
          <p>Served from image web-nginx {{ image_version }}.</p>

    - name: Record the image version
      ansible.builtin.copy:
        dest: /etc/image-release
        mode: "0644"
        content: "IMAGE_VERSION={{ image_version }}\n"

    - name: Check the Nginx configuration
      ansible.builtin.command: nginx -t
      changed_when: false
YAML

Ubuntu's /etc/nginx/nginx.conf already has a server_tokens line in its http block, and Nginx refuses a second one, so the playbook changes that line in place instead of adding the directive to hardening.conf. There is no task to enable the Nginx service: Ubuntu's package enables it at boot when it installs. The add_header lines sit at the http level, so every site inherits them unless a site sets its own add_header.

Last, a clean-up script. An image is copied onto every server, so anything left on it is copied too:

Bash
cat > scripts/cleanup.sh <<'SH'
#!/bin/sh
set -eu

apt-get -y autoremove --purge
apt-get clean
rm -rf /var/lib/apt/lists/*

# Let cloud-init run again on each new server, with fresh logs.
if command -v cloud-init >/dev/null 2>&1; then
  cloud-init clean --logs
fi

# Each server generates its own machine ID on first boot.
truncate -s 0 /etc/machine-id

# Drop the build's temporary SSH key. New servers get their own.
rm -f /home/ubuntu/.ssh/authorized_keys
SH

When the playbook grows past a handful of tasks, move it into a role; organise-ansible-work-into-roles shows how, and the provisioner below points at a playbook either way.

Check it worked

find ~/packer-image-demo -type f | sort lists six files: ansible/nginx.yml, plugins.pkr.hcl, scripts/base.sh, scripts/cleanup.sh, variables.pkr.hcl and web.pkr.hcl. ansible-playbook --syntax-check -i localhost, ansible/nginx.yml prints playbook: ansible/nginx.yml with no errors.

Step 5 · Add the build block and the manifest

The build block joins the source to the provisioners and adds a post-processor that writes a manifest.json file after every successful build:

Bash
cat > build.pkr.hcl <<'HCL'
build {
  name    = "web"
  sources = ["source.amazon-ebs.web"]

  provisioner "shell" {
    script           = "${path.root}/scripts/base.sh"
    environment_vars = ["DEBIAN_FRONTEND=noninteractive"]
    execute_command  = "chmod +x {{ .Path }}; sudo env {{ .Vars }} {{ .Path }}"
  }

  provisioner "ansible" {
    playbook_file    = "${path.root}/ansible/nginx.yml"
    user             = "ubuntu"
    use_proxy        = false
    extra_arguments  = ["--extra-vars", "image_version=${var.image_version}"]
    ansible_env_vars = ["ANSIBLE_HOST_KEY_CHECKING=False"]
  }

  provisioner "shell" {
    script           = "${path.root}/scripts/cleanup.sh"
    environment_vars = ["DEBIAN_FRONTEND=noninteractive"]
    execute_command  = "chmod +x {{ .Path }}; sudo env {{ .Vars }} {{ .Path }}"
  }

  post-processor "manifest" {
    output     = "${path.root}/manifest.json"
    strip_path = true
    custom_data = {
      image_version = var.image_version
      base_os       = "Ubuntu 26.04"
    }
  }
}
HCL

The ubuntu user on the build instance can use sudo without a password, so execute_command runs each script as root and passes environment_vars through. DEBIAN_FRONTEND=noninteractive stops apt from waiting for answers nobody is there to give. use_proxy = false lets Ansible connect straight to the instance with the SSH key Packer created, and switching off host key checking is safe here because the instance and its key exist only for this build.

The --extra-vars argument overrides the playbook's image_version default, so the version you pass to Packer ends up on the home page and in /etc/image-release.

Check it worked

ls ~/packer-image-demo/*.pkr.hcl lists four files: build.pkr.hcl, plugins.pkr.hcl, variables.pkr.hcl and web.pkr.hcl.

Step 6 · Format and validate the template

packer fmt rewrites files into the standard layout, and -check fails if any file still needs it, which makes it a good CI gate:

Bash
cd ~/packer-image-demo
packer fmt -recursive .
packer fmt -check -recursive .

packer validate reads the whole template, checks every block and attribute against the plugins, runs your variable validation, and confirms that the scripts, the playbook and ansible-playbook exist. It does not call AWS, so it needs no credentials:

Bash
packer validate -var image_version=1.0.0 .

Now try a bad version, to see your validation rule work:

Bash
packer validate -var image_version=v1 . || echo "Rejected, as intended"

Check it worked

The first packer fmt lists any file it reformatted; the -check run prints nothing. packer validate -var image_version=1.0.0 . prints The configuration is valid. The second validate prints an error containing The image_version must be three numbers separated by dots, followed by Rejected, as intended.

Step 7 · Build the image in your AWS account

A build costs money while it runs. Packer launches a real instance, which bills until Packer terminates it at the end of the build, usually a few minutes later. It also creates a temporary key pair and security group, both named packer_ followed by an ID, and deletes them at the end. What stays behind is the image and the EBS snapshot holding its disk, and the snapshot bills every month until you delete it. The last step shows how.

Packer reads AWS credentials the same way the AWS CLI does. Sign in with your profile (set-up-the-aws-cli-with-sso-and-named-profiles shows how to create one; replace dev with yours) and start the build:

Bash
aws sso login --profile dev
export AWS_PROFILE=dev
cd ~/packer-image-demo
packer build -var image_version=1.0.0 .

The account needs EC2 permissions to run instances, create images and snapshots, and manage key pairs and security groups. Packer's amazon plugin documentation lists the minimal IAM policy.

The output is prefixed with web.amazon-ebs.web: and walks through finding the source image, launching the instance, waiting for SSH, running each provisioner, stopping the instance and creating the image. Ansible's task list and recap appear in the middle. If you press Ctrl+C once, Packer stops and cleans up what it created; if the build is killed outright, see the last step for how to find leftovers.

Read the new image ID from the manifest:

Bash
jq '.builds[-1]' manifest.json
AMI_ID=$(jq -r '.builds[-1].artifact_id' manifest.json | cut -d: -f2)
echo "$AMI_ID"

Check it worked

The build ends with something like --> web.amazon-ebs.web: AMIs were created: followed by eu-west-2: ami-0123456789abcdef0. jq shows a build entry with "builder_type": "amazon-ebs", an artifact_id of the form eu-west-2:ami-... and your custom_data. In the EC2 console under AMIs, owned by you, the image appears with the ImageVersion tag 1.0.0.

Step 8 · Launch a server from the image and check it

Start one small instance from the new image. Replace sg-replace-me with a security group of yours that allows HTTP on port 80 from your IP:

Bash
INSTANCE_ID=$(aws ec2 run-instances --region eu-west-2 --image-id "$AMI_ID" \
  --instance-type t3.micro --security-group-ids sg-replace-me \
  --tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=web-nginx-check}]' \
  --query 'Instances[0].InstanceId' --output text)
aws ec2 wait instance-running --region eu-west-2 --instance-ids "$INSTANCE_ID"
PUBLIC_IP=$(aws ec2 describe-instances --region eu-west-2 --instance-ids "$INSTANCE_ID" \
  --query 'Reservations[0].Instances[0].PublicIpAddress' --output text)
curl -sI "http://$PUBLIC_IP/"
curl -s "http://$PUBLIC_IP/"

Give it a minute after instance-running for Nginx to come up. Notice there is no user data: Nginx, its config and the page were all on the disk before the server booted. To compare, the write-cloud-init-user-data-for-a-new-server tutorial does the same job at boot time.

When you have looked, terminate the instance so it stops billing:

Bash
aws ec2 terminate-instances --region eu-west-2 --instance-ids "$INSTANCE_ID"

Check it worked

The headers include Server: nginx with no version number after it, plus X-Content-Type-Options: nosniff and X-Frame-Options: DENY. The page body says Served from image web-nginx 1.0.0.

Step 9 · Delete the image and its snapshot

Deregistering an image does not delete the snapshot behind it, and the snapshot is what bills. Read the snapshot ID first, because once the image is gone you can no longer look it up from the image:

Bash
SNAPSHOT_ID=$(aws ec2 describe-images --region eu-west-2 --image-ids "$AMI_ID" \
  --query 'Images[0].BlockDeviceMappings[].Ebs.SnapshotId' --output text)
echo "$SNAPSHOT_ID"
aws ec2 deregister-image --region eu-west-2 --image-id "$AMI_ID"
aws ec2 delete-snapshot --region eu-west-2 --snapshot-id "$SNAPSHOT_ID"

If a build was killed before Packer could clean up, look for the temporary instance, key pair and security group. Each command prints an empty list when nothing is left:

Bash
aws ec2 describe-instances --region eu-west-2 \
  --filters Name=tag:Name,Values=packer-build-web Name=instance-state-name,Values=pending,running,stopped \
  --query 'Reservations[].Instances[].InstanceId'
aws ec2 describe-key-pairs --region eu-west-2 --filters 'Name=key-name,Values=packer_*' --query 'KeyPairs[].KeyName'
aws ec2 describe-security-groups --region eu-west-2 --filters 'Name=group-name,Values=packer_*' --query 'SecurityGroups[].GroupId'

Terminate or delete anything those return. Then remove the project, the plugins and the tools if you no longer need them:

Bash
cd ~
rm -rf ~/packer-image-demo
packer plugins remove github.com/hashicorp/amazon
packer plugins remove github.com/hashicorp/ansible
pipx uninstall ansible
sudo rm /usr/local/bin/packer

Check it worked

In the EC2 console, AMIs and Snapshots no longer list web-nginx-1.0.0-..., and the three leftover checks print []. ls ~/packer-image-demo reports that the folder does not exist, and command -v packer prints nothing.

Next steps

  • Add per-server settings at boot on top of the baked image with /tutorials/write-cloud-init-user-data-for-a-new-server.
  • Move the Nginx playbook into a reusable role with /tutorials/organise-ansible-work-into-roles, then point playbook_file at a playbook that applies it.
  • Launch and connect to servers from your image with /tutorials/launch-an-ec2-instance-and-connect.
  • Run packer fmt -check and packer validate on every pull request, and build a new image version when the playbook changes.

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.