Packer
HCL2 Templates Commands
Write Packer templates using HashiCorp Configuration Language 2 with sources, builds, and variables.
12 commands
Pro Tips
Use packer fmt to format HCL files consistently
Commands
Basic source block
$ source "amazon-ebs" "ubuntu" {
ami_name = "my-ami"
instance_type = "t2.micro"
region = "us-east-1"
source_ami_filter {
filters = { name = "ubuntu/images/*" }
owners = ["099720109477"]
most_recent = true
}
ssh_username = "ubuntu"
}
HCL2 source block example.
Build block
$ build {
sources = ["source.amazon-ebs.ubuntu"]
provisioner "shell" {
inline = ["sudo apt-get update"]
}
}
HCL2 build block example.
Variable definition
$ variable "region" {
type = string
default = "us-east-1"
}
HCL2 variable definition.
Locals block
$ locals {
timestamp = regex_replace(timestamp(), "[- TZ:]", "")
ami_name = "app-${local.timestamp}"
}
Define local values for reuse in templates.
Data source
$ data "amazon-ami" "base" {
filters = {
name = "ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*"
}
owners = ["099720109477"]
most_recent = true
}
HCL2 data source to look up AMIs.
File provisioner
$ provisioner "file" {
source = "config/app.conf"
destination = "/tmp/app.conf"
}
Upload files to the build instance.
Shell provisioner
$ provisioner "shell" {
scripts = [
"scripts/setup.sh",
"scripts/install-deps.sh"
]
environment_vars = [
"APP_ENV=production"
]
}
Run multiple shell scripts as provisioner.
Ansible provisioner
$ provisioner "ansible" {
playbook_file = "ansible/playbook.yml"
extra_arguments = [
"--extra-vars", "env=production"
]
}
Run Ansible playbook as provisioner.
Post-processor manifest
$ post-processor "manifest" {
output = "manifest.json"
strip_path = true
}
Generate build manifest with artifact IDs.
Docker source block
$ source "docker" "ubuntu" {
image = "ubuntu:22.04"
commit = true
changes = [
"ENTRYPOINT ["/app/start.sh"]"
]
}
HCL2 Docker source for container images.
Required plugins block
$ packer {
required_plugins {
amazon = {
version = ">= 1.2.0"
source = "github.com/hashicorp/amazon"
}
}
}
Declare required plugins with version constraints.
PowerShell provisioner
$ provisioner "powershell" {
inline = [
"Install-WindowsFeature -Name Web-Server",
"Set-Service -Name W3SVC -StartupType Automatic"
]
}
Run PowerShell commands on Windows builds.