Chuyển đến nội dung

Bài 11 · Builders and Provisioners

Packer amazon-ebs Builder: Build an AMI Step by Step

Build AWS AMIs with Packer: credentials, the amazon-ebs source, looking up the newest base AMI, naming with timestamps, tags, encryption, multi-region copies and IAM permissions.

The amazon-ebs builder creates an Amazon Machine Image backed by Elastic Block Store volumes. It is the most used Packer builder. It launches a temporary EC2 instance from a base AMI, lets you provision it, stops it, creates a new AMI from its root volume and terminates the instance. This lesson takes you from credentials to a production-quality source block.

AWS is not reachable from this site and Packer cannot run here, so every HCL example is read-only and no real AWS output is shown. Never paste real account IDs or keys into templates. A Python stand-in models AMI name formatting and base-image selection.

What you need in AWS

  1. An AWS account and a region.
  2. Credentials that Packer can find: environment variables (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN), a shared profile (AWS_PROFILE, set profile in the source), or an instance/role credential when running in CI. Prefer short-lived credentials (SSO, OIDC, assumed roles) over long-lived keys.
  3. A network for the temporary instance: the default VPC works for learning. In locked-down accounts specify vpc_id and subnet_id.
  4. IAM permissions for EC2: describing images, running and terminating instances, creating/deleting key pairs and security groups, creating images and snapshots, tagging. HashiCorp documents a minimal policy; start from it and tighten.

A minimal source

HCL
packer {
  required_plugins {
    amazon = {
      version = ">= 1.3.0, < 2.0.0"
      source  = "github.com/hashicorp/amazon"
    }
  }
}

source "amazon-ebs" "web" {
  region        = "eu-west-1"
  instance_type = "t3.micro"
  ssh_username  = "ubuntu"
  ami_name      = "web-base-v1"

  source_ami_filter {
    filters = {
      name                = "ubuntu/images/hvm-ssd-gp3/ubuntu-noble-24.04-amd64-server-*"
      root-device-type    = "ebs"
      virtualization-type = "hvm"
    }
    owners      = ["099720109477"]   # Canonical's AWS account
    most_recent = true
  }
}

build {
  sources = ["source.amazon-ebs.web"]

  provisioner "shell" {
    inline = [
      "sudo apt-get update",
      "sudo apt-get install -y nginx",
    ]
  }
}

Field by field:

  • region: where the temporary instance runs and the AMI is created.
  • instance_type: size of the build instance (this is not the size your servers will use). A small type is enough unless you compile things.
  • ssh_username: the login user of the base image (ubuntu, ec2-user on Amazon Linux, admin on Debian, centos...).
  • ami_name: must be unique per region and account. A second build with the same name fails.
  • source_ami_filter: picks the base AMI dynamically; owners limits to a trusted publisher, most_recent chooses the newest match. Alternatively set source_ami = "ami-..." to pin an exact image.

Without most_recent and owners, a filter could match another account's image. Always set both.

Unique names with timestamps

HCL
locals {
  timestamp = regex_replace(timestamp(), "[- TZ:]", "")
}

source "amazon-ebs" "web" {
  ami_name = "web-base-${local.timestamp}"
  # ...
}

timestamp() returns something like 2025-01-31T12:00:00Z; the regex strips separators so the name contains only digits. AMI names allow letters, digits, spaces and a few symbols, 3 to 128 characters. See Locals and expressions for functions like this one.

A stand-in for names and base images

This Python stand-in validates AMI-style names (the rule above) and mimics most_recent selection from a made-up list of images. The data is invented.

Python Stand-in: AMI names and most_recent

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The second line shows why owners matters: without it the newest match may belong to a stranger.

Tags

HCL
source "amazon-ebs" "web" {
  # ...
  tags = {
    Name        = "web-base"
    Environment = var.env
    BuiltBy     = "packer"
    SourceAMI   = "{{ .SourceAMI }}"
  }

  snapshot_tags = {
    BuiltBy = "packer"
  }

  run_tags = {
    Purpose = "packer-build"       # tags on the temporary instance
  }
}

tags go on the AMI, snapshot_tags on its snapshots and run_tags on the temporary instance, which helps you find and sweep orphans after a crash. The {{ .SourceAMI }} template placeholder is filled by the builder at build time (a builder-level interpolation that HCL2 still supports in these strings).

Disks and encryption

HCL
source "amazon-ebs" "web" {
  # ...
  encrypt_boot = true
  kms_key_id   = "alias/golden-images"

  launch_block_device_mappings {
    device_name           = "/dev/sda1"
    volume_size           = 20
    volume_type           = "gp3"
    delete_on_termination = true
  }
}

Set the root volume size here; images inherit it as a minimum. encrypt_boot = true creates an encrypted AMI. Encrypted AMIs can be shared only if you share the KMS key too.

Copying and sharing

HCL
source "amazon-ebs" "web" {
  # ...
  ami_regions = ["us-east-1", "eu-central-1"]   # copy the finished AMI to these regions
  ami_users   = ["123456789012"]                # share with these account IDs
  ami_description = "Web base image built by Packer"
}

Copies make the build longer. Copying to many regions is common for global autoscaling groups.

Cleaning up old images

force_deregister = true and force_delete_snapshot = true replace an existing AMI of the same name, which is handy for development but dangerous in production. Better: name images uniquely and delete old ones on a schedule with a lifecycle policy (EC2 Image Builder or Data Lifecycle Manager) or a small script that keeps the last N images.

Connection settings

HCL
source "amazon-ebs" "web" {
  # ...
  temporary_key_pair_type = "ed25519"
  ssh_timeout             = "10m"
  associate_public_ip_address = true     # needed when building in a public subnet with no VPN
  ssh_interface           = "public_ip"  # or private_ip / session_manager
}

For fully private builds, use a private subnet with ssh_interface = "session_manager" (needs the SSM agent and an instance profile with the right permissions) instead of opening port 22 to the internet.

What happens in AWS during a build

sequenceDiagram
  participant P as Packer
  participant E as EC2
  P->>E: create temporary key pair and security group
  P->>E: run instance from the base AMI
  P->>E: connect over SSH, run provisioners
  P->>E: stop instance
  P->>E: create image (AMI + snapshot)
  P->>E: wait until available, copy and share if asked
  P->>E: terminate instance, delete key pair and group

The temporary resources exist only for the duration of the build.

Common errors

  • AMI name already exists: add a timestamp or version to ami_name.
  • UnauthorizedOperation: the credentials lack an EC2 permission; the error names the action.
  • Timeout waiting for SSH: wrong ssh_username, no route from your network to the instance, a security group blocking port 22 or a subnet without a public IP.
  • No matching source AMI: the filter or region is wrong; test with the AWS CLI command aws ec2 describe-images using the same filters.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Why must ami_name be unique?

    AWS rejects a second AMI with the same name in the same region unless the old one is deregistered (force_deregister).
  2. 2. Which two settings should always accompany source_ami_filter with most_recent = true?

    owners restricts the search to a trusted publisher; the name filter narrows which image family you mean.
  3. 3. Where do run_tags appear?

    run_tags mark the build instance, which makes orphans easy to find.
  4. 4. What does ami_regions do?

    After the AMI is created in region, Packer copies it to each region in ami_regions.

Summary

  • amazon-ebs launches a temporary instance, provisions it, creates an AMI and cleans up.
  • Pick the base image with source_ami_filter (always set owners and most_recent) or pin source_ami.
  • Make ami_name unique with a timestamp; use tags, snapshot_tags and run_tags for traceability and cleanup.
  • Encrypt with encrypt_boot, size the root volume with launch_block_device_mappings, copy with ami_regions.
  • Prefer short-lived credentials and Session Manager over open SSH and long-lived keys.

Next: VM builders: QEMU, VirtualBox and VMware

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.