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 rebuild. This page explains each stage with a complete, working HCL2 template for an AWS AMI, the commands to run, the output to expect, and fixes for the errors you are most likely to hit.
The workflow for using HashiCorp Packer typically involves the following steps:
- Create a Packer template: A Packer template is a JSON file that defines the configuration for building a machine image. The template specifies the builders, provisioners, and post-processors to use, as well as the configuration options for each.
- Run
packer build: Use thepacker buildcommand to execute the Packer template and create the machine image. During the build process, Packer will run the builders to create a new virtual machine, use the provisioners to configure the virtual machine, and then create the machine image in the specified format. - Test the machine image: Once the machine image has been created, it can be tested to ensure that it is functioning correctly. This may involve running automated tests or manually verifying that the image is working as expected.
- Distribute the machine image: The machine image can be distributed to various cloud providers, virtualization platforms, or container systems. This may involve uploading the image to a cloud storage service, such as Amazon S3 or Google Cloud Storage, or creating a custom image in a virtualization platform like VMware or VirtualBox.
- Update the Packer template: If changes need to be made to the machine image, such as adding new software or updating configurations, the Packer template can be updated and the
packer buildcommand can be run again to create a new image.


What has changed since the steps above were written
The steps above describe the Packer template as a JSON file. JSON still works, but HCL2 (files ending in .pkr.hcl) has been the recommended format since Packer 1.7, and newer features such as required_plugins and packer init only work with HCL2. Since plugins were split out of the Packer binary, a modern workflow also needs packer init before the first build, plus packer fmt and packer validate to catch mistakes early.
| Stage | Command | Purpose |
|---|---|---|
| Write template | (editor) | Define plugins, variables, sources and build steps in *.pkr.hcl |
| Initialise | packer init . |
Download the plugins listed in required_plugins |
| Format | packer fmt . |
Rewrite files in canonical HCL style |
| Validate | packer validate . |
Check syntax and configuration before spending money on a build |
| Build | packer build . |
Launch a temporary machine, provision it, capture the image, clean up |
| Test | (launch from the image) | Confirm the image boots and the software works |
| Distribute | template settings or registry | Copy or share the image to regions, accounts or teams |
| Iterate | edit, commit, rebuild | Produce a new versioned image for every change |
Prerequisites
- Packer installed and on your
PATH. Check it withpacker version. - An AWS account and credentials Packer can read: environment variables, a profile in
~/.aws/credentials, or an IAM role if you run Packer on EC2 or in CI. - IAM permissions to run and stop instances, create and delete security groups and key pairs, and create images and snapshots.
- A default VPC in the target region, or
vpc_idandsubnet_idset in the source block.
Note: Do not put access keys in the template. The Amazon plugin uses the standard AWS credential chain, so the template stays safe to commit.
Step 1: write an HCL2 template
Create a directory such as ubuntu-nginx/ and save the following as ubuntu-nginx.pkr.hcl. It builds an Ubuntu 22.04 AMI with Nginx installed.
packer {
required_plugins {
amazon = {
version = ">= 1.2.0"
source = "github.com/hashicorp/amazon"
}
}
}
variable "region" {
type = string
default = "us-east-1"
}
variable "instance_type" {
type = string
default = "t3.micro"
}
locals {
timestamp = regex_replace(timestamp(), "[- TZ:]", "")
}
source "amazon-ebs" "ubuntu" {
region = var.region
instance_type = var.instance_type
ssh_username = "ubuntu"
ami_name = "ubuntu-nginx-${local.timestamp}"
source_ami_filter {
filters = {
name = "ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*"
root-device-type = "ebs"
virtualization-type = "hvm"
}
owners = ["099720109477"]
most_recent = true
}
tags = {
Name = "ubuntu-nginx"
BuiltBy = "packer"
BuildTime = local.timestamp
}
}
build {
name = "web"
sources = ["source.amazon-ebs.ubuntu"]
provisioner "shell" {
inline = [
"cloud-init status --wait",
"sudo apt-get update",
"sudo DEBIAN_FRONTEND=noninteractive apt-get install -y nginx",
"sudo systemctl enable nginx"
]
}
post-processor "manifest" {
output = "manifest.json"
strip_path = true
}
}Code language: PHP (php)
packerblock: pins the Amazon plugin sopacker initcan install it and every build uses a known version.variableblocks: inputs you can override with-varor a*.pkrvars.hclfile.locals: a timestamp so each AMI name is unique. AMI names must be unique per account and region.sourceblock: the builder.source_ami_filterpicks the newest official Canonical image rather than a hard-coded AMI ID that goes stale.buildblock: connects sources to provisioners.cloud-init status --waitstops apt from clashing with first-boot package jobs.manifestpost-processor: writes the resulting AMI ID tomanifest.jsonso CI jobs or Terraform can pick it up.
Step 2: initialise, format and validate
cd ubuntu-nginx
packer init .
packer fmt .
packer validate .
packer init downloads the plugin into the Packer plugin directory and only needs to run again when required_plugins changes. A clean template validates with The configuration is valid. Add validation to every pull request: it costs nothing and catches typos before a build launches billable instances.
Step 3: build the image
packer build .
packer build -var 'region=eu-west-1' -var 'instance_type=t3.small' .
packer build -var-file=prod.pkrvars.hcl .Code language: PHP (php)
Packer creates a temporary key pair and security group, launches an instance from the source AMI, connects over SSH, runs the provisioners, stops the instance, registers the AMI, and then deletes the temporary resources. A successful run ends like this:
==> Wait completed after 4 minutes 12 seconds
==> Builds finished. The artifacts of successful builds are:
--> web.amazon-ebs.ubuntu: AMIs were created:
us-east-1: ami-0abc1234def567890Code language: PHP (php)
Note: Files named *.auto.pkrvars.hcl are loaded automatically. Use -on-error=ask while developing so Packer pauses on failure and you can SSH into the instance to debug instead of having it destroyed right away.
Step 4 and 5: test and distribute the image
To test, launch an instance from the new AMI and check the result, either by hand or with a test tool your team already uses. You can also put test commands in a final shell provisioner so that a failing check stops the build before an AMI is registered.
provisioner "shell" {
inline = [
"systemctl is-enabled nginx",
"sudo nginx -t"
]
}Code language: JavaScript (javascript)
The steps above suggest distributing images by uploading them to Amazon S3 or Google Cloud Storage. For cloud builders, that is not how it usually works: Packer registers the image directly in the platform (an AMI in EC2, a managed image in Azure, an image in GCE). You distribute it by copying and sharing it, which the template can do for you:
source "amazon-ebs" "ubuntu" {
ami_regions = ["eu-west-1", "ap-south-1"]
ami_users = ["111122223333"]
}Code language: PHP (php)
Downstream tools then use the AMI ID from manifest.json, or look it up by tag or name pattern, for example with a Terraform aws_ami data source.
Common errors and fixes
| Error | Cause | Fix |
|---|---|---|
Missing plugins / unknown source type |
packer init not run, or the plugin is missing from required_plugins |
Add the plugin block and run packer init . |
No valid credential sources found |
No AWS credentials available to Packer | Export AWS_PROFILE or credentials, or attach an IAM role |
Timeout waiting for SSH |
No public IP, a blocked security group, the wrong ssh_username, or no default VPC |
Check the subnet and routing, set associate_public_ip_address = true, and use ubuntu for Ubuntu images |
AMI Name ... is used by an existing AMI |
A fixed ami_name was reused |
Add a timestamp to the name, or use -force to deregister the old AMI |
Could not get lock /var/lib/dpkg/lock-frontend |
cloud-init or unattended upgrades still running | Run cloud-init status --wait before apt commands |
UnauthorizedOperation |
IAM policy missing EC2 actions | Grant the minimum EC2 permissions listed in the Amazon plugin documentation |
For anything else, set PACKER_LOG=1 before packer build to get detailed logs, and add PACKER_LOG_PATH=packer.log to write them to a file.
Best practices for the iterate step
- Keep templates in Git and build from CI (
init,fmt -check,validate,build), so every image comes from a reviewed commit. - Treat images as immutable. Change the template and rebuild rather than patching running servers.
- Add the Git commit SHA and build time to image tags so you can trace any running instance back to its source.
- Rebuild on a schedule, not only when the template changes, so new images pick up OS security patches.
- Deregister old AMIs and delete their snapshots. EBS snapshots keep costing money after you stop using the AMI.
- Mark secret variables
sensitive = trueso Packer hides them in output, and remove temporary credentials or keys before the image is captured. - Convert legacy JSON templates with
packer hcl2_upgrade template.json, then review the generated.pkr.hclfile.
Frequently asked questions
Should Packer templates be written in JSON or HCL2?
Use HCL2. JSON templates still work, but HCL2 is the recommended format and is needed for features such as required_plugins and packer init. You can convert existing files with packer hcl2_upgrade.
What is the difference between a builder, a provisioner and a post-processor?
A builder (a source block in HCL2) creates the temporary machine and captures the image. A provisioner configures that machine, for example with shell scripts or Ansible. A post-processor acts on the finished artifact, for example by writing a manifest, compressing it or importing it somewhere else.
Why does packer build fail with a missing plugin error?
Since plugins were split out of the core binary, most builders must be declared in required_plugins and installed with packer init . before building. Run init again whenever you add or change a plugin.
Does Packer delete the temporary EC2 instance after a build?
Yes. On success, and by default on failure too, Packer terminates the instance and removes the temporary key pair and security group. Use -on-error=ask or -on-error=abort to keep it for debugging, and clean it up yourself afterwards.
How do Terraform and Packer work together?
Packer builds the image, and Terraform deploys infrastructure that uses it. Terraform usually finds the newest image through a data source filtered by name or tags, or reads the AMI ID from Packer’s manifest output.
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
PakarPBN
A Private Blog Network (PBN) is a collection of websites that are controlled by a single individual or organization and used primarily to build backlinks to a “money site” in order to influence its ranking in search engines such as Google. The core idea behind a PBN is based on the importance of backlinks in Google’s ranking algorithm. Since Google views backlinks as signals of authority and trust, some website owners attempt to artificially create these signals through a controlled network of sites.
In a typical PBN setup, the owner acquires expired or aged domains that already have existing authority, backlinks, and history. These domains are rebuilt with new content and hosted separately, often using different IP addresses, hosting providers, themes, and ownership details to make them appear unrelated. Within the content published on these sites, links are strategically placed that point to the main website the owner wants to rank higher. By doing this, the owner attempts to pass link equity (also known as “link juice”) from the PBN sites to the target website.
The purpose of a PBN is to give the impression that the target website is naturally earning links from multiple independent sources. If done effectively, this can temporarily improve keyword rankings, increase organic visibility, and drive more traffic from search results.
Streaming Film
Nonton Film gratis
Jasa Backlink
Download Anime Batch