This tutorial uses a HashiCorp Packer HCL2 template to build a custom Amazon Machine Image (AMI). The template starts from Ubuntu 22.04 in the ap-south-1 (Mumbai) region and installs Redis on it. Below the example you will find an explanation of each block, a corrected template that still builds today, the commands to run, the errors you are likely to hit, and how to clean up afterwards.
What the example template does
Packer starts a temporary EC2 instance from a base AMI and connects to it over SSH. It runs your provisioners on that instance, then stops it and saves the result as a new AMI. It also deletes the temporary instance, key pair and security group it created. The template in the example above has three top-level blocks:
| Block | Purpose |
|---|---|
packer { required_plugins } | Declares the Amazon plugin (github.com/hashicorp/amazon). packer init downloads it. |
source "amazon-ebs" "ubuntu" | Defines the builder: region, instance type, base AMI lookup (source_ami_filter), SSH user and the name of the AMI to create. |
source_ami_filter | Finds the base image. 099720109477 is Canonical's AWS account ID, so only official Ubuntu images match. most_recent = true picks the newest match. |
build | Links the source to provisioners. The shell provisioner runs the inline commands on the temporary instance. |
environment_vars | Exports FOO=hello world into the provisioner shell. That is why example.txt ends up containing FOO is hello world. |
The amazon-ebs builder produces an EBS-backed AMI. Its root volume is stored as an EBS snapshot in your account, and you are charged for that snapshot until you delete it.
Prerequisites
- Packer installed locally. Check with
packer version. The template uses HCL2 andrequired_plugins, so it needs a reasonably recent Packer release. - An AWS account and credentials that Packer can find: an
AWS_PROFILE, theAWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEYenvironment variables, SSO, or an instance role. Packer uses the standard AWS SDK credential chain. - IAM permissions to run, stop and terminate instances; create and delete key pairs, security groups, volumes and snapshots; and register, describe and tag images. The Packer Amazon plugin documentation publishes a minimal policy.
- A default VPC in the target region with a public subnet, or a
subnet_idyou specify that can reach the internet. Packer needs SSH access to the instance, andapt-getneeds outbound internet access. - Optional: the AWS CLI, used below to verify and clean up the AMI.
Corrected and improved template
The original template has some problems. Its base-image filter points at a single dated 2022 image. Its AMI name is fixed, so a second build fails. It has empty credential fields, and it uses a fixed sleep to wait for the instance to be ready. Save the version below as aws-ubuntu.pkr.hcl:
packer {
required_plugins {
amazon = {
version = ">= 1.1.1"
source = "github.com/hashicorp/amazon"
}
}
}
variable "region" {
type = string
default = "ap-south-1"
}
variable "instance_type" {
type = string
default = "t2.micro"
}
locals {
timestamp = regex_replace(timestamp(), "[- TZ:]", "")
}
source "amazon-ebs" "ubuntu" {
ami_name = "learn-packer-ubuntu-redis-${local.timestamp}"
instance_type = var.instance_type
region = var.region
source_ami_filter {
filters = {
name = "ubuntu/images/*ubuntu-jammy-22.04-amd64-server-*"
root-device-type = "ebs"
virtualization-type = "hvm"
}
most_recent = true
owners = ["099720109477"]
}
ssh_username = "ubuntu"
tags = {
Name = "learn-packer-ubuntu-redis"
Base_AMI_Name = "{{ .SourceAMIName }}"
BuiltBy = "packer"
}
}
build {
name = "learn-packer"
sources = ["source.amazon-ebs.ubuntu"]
provisioner "shell" {
environment_vars = [
"FOO=hello world",
]
inline = [
"echo Waiting for cloud-init to finish",
"cloud-init status --wait || true",
"echo Installing Redis",
"sudo apt-get update",
"sudo DEBIAN_FRONTEND=noninteractive apt-get install -y redis-server",
"echo \"FOO is $FOO\" > example.txt",
]
}
}Code language: JavaScript (javascript)
- Wildcard AMI filter:
ubuntu/images/*ubuntu-jammy-22.04-amd64-server-*matches every Jammy release, somost_recent = trueselects the latest patched image. In the original,most_recenthad no effect because the filter matched one exact, dated image. AWS deprecates older AMIs, and Packer leaves deprecated images out of filter results by default, so that exact image can stop matching. - Unique AMI name: AMI names must be unique per account and region. The timestamp suffix lets you run the build again without deleting the previous image first.
- No credential fields: the empty
access_keyandsecret_keylines are removed. Never put real keys in a template. Packer reads credentials from the environment or your AWS profile. cloud-init status --waitreplacessleep 30. It waits exactly as long as first-boot setup needs, which avoidsaptlock errors. The|| trueis there because newer cloud-init versions return a non-zero exit code for warnings that are not fatal.DEBIAN_FRONTEND=noninteractiveis placed aftersudo.sudoclears most environment variables, so setting it beforesudowould not reachapt-get. Setting it here stops package prompts from stalling the build.- Variables and tags let you change the region or instance size without editing the file, and make the image easy to find later.
Build the AMI
- Set your credentials, for example
export AWS_PROFILE=dev. - Run
packer init .to download the Amazon plugin declared inrequired_plugins. - Run
packer fmt .to normalise indentation. The original file mixes tabs and spaces. - Run
packer validate .to check syntax and required arguments before you spend money on an instance. - Run
packer build aws-ubuntu.pkr.hcl. To override a variable, add for example-var 'region=us-east-1'.
packer init .
packer fmt .
packer validate .
packer build aws-ubuntu.pkr.hclCode language: CSS (css)
A successful build usually takes a few minutes. It ends with output similar to this (IDs will differ):
==> learn-packer.amazon-ebs.ubuntu: Creating AMI learn-packer-ubuntu-redis-20261130120000 from instance i-0abc123...
==> learn-packer.amazon-ebs.ubuntu: Terminating the source AWS instance...
==> learn-packer.amazon-ebs.ubuntu: Deleting temporary security group...
==> learn-packer.amazon-ebs.ubuntu: Deleting temporary keypair...
Build 'learn-packer.amazon-ebs.ubuntu' finished after 5 minutes 12 seconds.
==> Builds finished. The artifacts of successful builds are:
--> learn-packer.amazon-ebs.ubuntu: AMIs were created:
ap-south-1: ami-0123456789abcdef0Code language: PHP (php)
Note: Set PACKER_LOG=1 before packer build to get verbose logs. Add -on-error=ask to keep the temporary instance running after a failure so you can SSH in and debug it.
Verify and use the new AMI
List the images you own that match the naming pattern:
aws ec2 describe-images --owners self --region ap-south-1 \
--filters "Name=name,Values=learn-packer-ubuntu-redis-*" \
--query 'Images[].[ImageId,Name,CreationDate]' --output tableCode language: PHP (php)
Launch an instance from the AMI and SSH in as ubuntu. Then run systemctl status redis-server and redis-cli ping, which should reply PONG. Also run cat ~/example.txt, which should print FOO is hello world. The AMI can be referenced from a launch template; see AWS Tutorials: Auto Scaling Group for using a custom image at scale.
Common errors and fixes
| Error | Cause | Fix |
|---|---|---|
Missing plugins / unknown source type amazon-ebs | packer init was not run | Run packer init . in the template directory |
No AMI was found matching filters | The filter names one dated image that is now deprecated, or the region or owner is wrong | Use the wildcard filter shown above and check that owners is 099720109477 |
AMI Name: '...' is used by an existing AMI | Fixed ami_name from an earlier build | Add the timestamp suffix, or deregister the old AMI first |
NoCredentialProviders or no valid providers in chain | Packer cannot find AWS credentials | Export AWS_PROFILE or the access key variables, then check with aws sts get-caller-identity |
UnauthorizedOperation | The IAM identity lacks an EC2 permission | Attach the minimal Packer policy from the plugin documentation |
Timeout waiting for SSH | No default VPC, a private subnet, or no public IP | Set subnet_id and associate_public_ip_address = true, or use Session Manager with ssh_interface = "session_manager" |
Could not get lock /var/lib/dpkg/lock-frontend | cloud-init or unattended-upgrades is still running apt | Keep cloud-init status --wait before running apt-get |
Clean up and best practices
Each build leaves an AMI and an EBS snapshot that you keep paying for. Deregistering an AMI does not delete its snapshot, so remove both:
AMI_ID=ami-0123456789abcdef0
SNAP_ID=$(aws ec2 describe-images --image-ids "$AMI_ID" --region ap-south-1 \
--query 'Images[0].BlockDeviceMappings[0].Ebs.SnapshotId' --output text)
aws ec2 deregister-image --image-id "$AMI_ID" --region ap-south-1
aws ec2 delete-snapshot --snapshot-id "$SNAP_ID" --region ap-south-1Code language: JavaScript (javascript)
- Keep the template in Git and run
packer fmt -checkandpacker validatein CI. - Move long inline commands into a
scriptfile, or into Ansible, once provisioning goes beyond a few lines. - Pin the plugin to a major version (for example
~> 1) so that an incompatible new major version is not picked up silently. - Use
ami_regionsto copy the image to other regions, andami_usersto share it with other accounts in your organisation. - Rebuild images regularly so they pick up security patches, rather than patching long-running instances.
- Find more image and automation guides under Infrastructure as Code tutorials.
Frequently asked questions
Why does Packer say no AMI was found matching filters?
The filter must match at least one image that is available in your region. A filter naming one dated image, such as the 20220912 Jammy build, stops matching once AWS deprecates that image, because deprecated images are excluded by default. Use a wildcard name pattern with most_recent = true.
Do I need to put AWS access keys in the Packer template?
No. Packer uses the standard AWS credential chain: environment variables, shared config profiles, SSO and instance roles. Leave access_key and secret_key out, so that secrets never end up in source control.
How do I build an Ubuntu 24.04 AMI instead of 22.04?
Change the filter name to ubuntu/images/*ubuntu-noble-24.04-amd64-server-* and keep Canonical's owner ID 099720109477. The wildcard after images/ matches both of the storage paths Canonical uses in image names.
Can I run packer build twice with the same template?
Only if the AMI name changes each time, because AMI names must be unique per account and region. Add a timestamp to ami_name as shown above, or set force_deregister = true and force_delete_snapshot = true to replace the previous image.
Does Packer delete the EC2 instance it creates?
Yes. It terminates the temporary instance and removes the temporary key pair and security group, unless you pass -on-error=abort or choose to keep them with -on-error=ask. The AMI and its snapshot stay in your account until you delete them.
Related tutorials
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services โ all in one place.
Explore Hospitals