MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Hashicorp Packer Example Program: AWS AMI

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:

BlockPurpose
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_filterFinds the base image. 099720109477 is Canonical's AWS account ID, so only official Ubuntu images match. most_recent = true picks the newest match.
buildLinks the source to provisioners. The shell provisioner runs the inline commands on the temporary instance.
environment_varsExports 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 and required_plugins, so it needs a reasonably recent Packer release.
  • An AWS account and credentials that Packer can find: an AWS_PROFILE, the AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY environment 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_id you specify that can reach the internet. Packer needs SSH access to the instance, and apt-get needs 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, so most_recent = true selects the latest patched image. In the original, most_recent had 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_key and secret_key lines are removed. Never put real keys in a template. Packer reads credentials from the environment or your AWS profile.
  • cloud-init status --wait replaces sleep 30. It waits exactly as long as first-boot setup needs, which avoids apt lock errors. The || true is there because newer cloud-init versions return a non-zero exit code for warnings that are not fatal.
  • DEBIAN_FRONTEND=noninteractive is placed after sudo. sudo clears most environment variables, so setting it before sudo would not reach apt-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

  1. Set your credentials, for example export AWS_PROFILE=dev.
  2. Run packer init . to download the Amazon plugin declared in required_plugins.
  3. Run packer fmt . to normalise indentation. The original file mixes tabs and spaces.
  4. Run packer validate . to check syntax and required arguments before you spend money on an instance.
  5. 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

ErrorCauseFix
Missing plugins / unknown source type amazon-ebspacker init was not runRun packer init . in the template directory
No AMI was found matching filtersThe filter names one dated image that is now deprecated, or the region or owner is wrongUse the wildcard filter shown above and check that owners is 099720109477
AMI Name: '...' is used by an existing AMIFixed ami_name from an earlier buildAdd the timestamp suffix, or deregister the old AMI first
NoCredentialProviders or no valid providers in chainPacker cannot find AWS credentialsExport AWS_PROFILE or the access key variables, then check with aws sts get-caller-identity
UnauthorizedOperationThe IAM identity lacks an EC2 permissionAttach the minimal Packer policy from the plugin documentation
Timeout waiting for SSHNo default VPC, a private subnet, or no public IPSet 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-frontendcloud-init or unattended-upgrades is still running aptKeep 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 -check and packer validate in CI.
  • Move long inline commands into a script file, 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_regions to copy the image to other regions, and ami_users to 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

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
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.

Related Posts

Quick Tutorials of Hashicorp Packer

Packer AWS – Builders & Provisionars – aws-ubuntu.pkr.hcl Rajesh Kumar I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge,…

Read More

How to overwrite Existing AWS EC2 AMI with Packer?

USING FORCE_DEREGISTER ADDED IN V1.1.2, IT WAS VERIFIED WHETHER AWS EC2 AMI CAN BE OVERWRITTEN. THE PROCESS IS TO DELETE THE AMI WITH THE SAME NAME AND…

Read More

Packer Tutorials: Hashipcorp Packer workflow

The HashiCorp Packer workflow is a repeatable cycle: write a template, initialise plugins, validate it, build the image, test it, distribute it, then change the template and…

Read More

Packer Tutorials: Packer Commands reference with its use cases & Example

This page is a working reference for the HashiCorp Packer CLI: init, fmt, validate, inspect, build, console, plugins, hcl2_upgrade and the legacy fix command, each with real…

Read More

AWS Tutorials: AWS CodeBuild – Buildspec code for creating AMI from running instances

This page has an AWS CodeBuild buildspec that finds every running EC2 instance tagged environment=uat and creates an AMI from each one with the AWS CLI. It…

Read More

Packer Tutorials: Amazon Secrets Manager Data Source – amazon-secretsmanager

The amazon-secretsmanager data source lets a Packer HCL2 template read a secret from AWS Secrets Manager during a build, so passwords and tokens stay out of your…

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x