Packer
Comprehensive HashiCorp Packer commands and workflows for automated machine image building across multiple platforms.
Installation & Setup
Command |
Description |
packer version |
Show Packer version |
packer -help |
Show help information |
packer -help build |
Show help for specific command |
Core Commands
Build Operations
Command |
Description |
packer build template.pkr.hcl |
Build image from template |
packer build -var 'region=us-west-2' template.pkr.hcl |
Build with variables |
packer build -var-file=vars.pkrvars.hcl template.pkr.hcl |
Build with variable file |
packer build -only=amazon-ebs template.pkr.hcl |
Build specific builder only |
packer build -except=virtualbox-iso template.pkr.hcl |
Exclude specific builder |
Validation and Inspection
Command |
Description |
packer validate template.pkr.hcl |
Validate template |
packer inspect template.pkr.hcl |
Inspect template |
packer fmt template.pkr.hcl |
Format template |
packer fmt -diff template.pkr.hcl |
Show formatting differences |
Plugin Management
Command |
Description |
packer init template.pkr.hcl |
Initialize and install plugins |
packer plugins install github.com/hashicorp/amazon |
Install specific plugin |
packer plugins installed |
List installed plugins |
Template Examples
AWS AMI Template
packer \\\\{
required_plugins \\\\{
amazon = \\\\{
version = ">= 1.0.0"
source = "github.com/hashicorp/amazon"
\\\\}
\\\\}
\\\\}
variable "region" \\\\{
type = string
default = "us-west-2"
\\\\}
variable "instance_type" \\\\{
type = string
default = "t2.micro"
\\\\}
locals \\\\{
timestamp = regex_replace(timestamp(), "[- TZ:]", "")
\\\\}
source "amazon-ebs" "ubuntu" \\\\{
ami_name = "my-ubuntu-$\\\\{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 = "MyUbuntuImage"
Environment = "production"
\\\\}
\\\\}
build \\\\{
name = "ubuntu-build"
sources = [
"source.amazon-ebs.ubuntu"
]
provisioner "shell" \\\\{
inline = [
"echo 'Updating system packages'",
"sudo apt-get update",
"sudo apt-get upgrade -y",
"sudo apt-get install -y nginx docker.io",
"sudo systemctl enable nginx",
"sudo systemctl enable docker"
]
\\\\}
provisioner "file" \\\\{
source = "files/nginx.conf"
destination = "/tmp/nginx.conf"
\\\\}
provisioner "shell" \\\\{
inline = [
"sudo mv /tmp/nginx.conf /etc/nginx/nginx.conf",
"sudo nginx -t"
]
\\\\}
post-processor "manifest" \\\\{
output = "manifest.json"
strip_path = true
\\\\}
\\\\}
Azure Image Template
source "azure-arm" "ubuntu" \\\\{
client_id = var.client_id
client_secret = var.client_secret
subscription_id = var.subscription_id
tenant_id = var.tenant_id
managed_image_resource_group_name = "myResourceGroup"
managed_image_name = "myUbuntuImage"
os_type = "Linux"
image_publisher = "Canonical"
image_offer = "0001-com-ubuntu-server-jammy"
image_sku = "22_04-lts"
location = "East US"
vm_size = "Standard_B2s"
\\\\}
Google Cloud Image Template
source "googlecompute" "ubuntu" \\\\{
project_id = var.project_id
source_image = "ubuntu-2204-jammy-v20230114"
zone = "us-central1-a"
image_name = "my-ubuntu-image"
image_description = "Custom Ubuntu image with applications"
ssh_username = "packer"
tags = ["packer", "ubuntu"]
\\\\}
Docker Image Template
source "docker" "ubuntu" \\\\{
image = "ubuntu:22.04"
commit = true
changes = [
"EXPOSE 80",
"ENTRYPOINT [\"/usr/sbin/nginx\", \"-g\", \"daemon off;\"]"
]
\\\\}
build \\\\{
sources = ["source.docker.ubuntu"]
provisioner "shell" \\\\{
inline = [
"apt-get update",
"apt-get install -y nginx",
"rm -rf /var/lib/apt/lists/*"
]
\\\\}
post-processor "docker-tag" \\\\{
repository = "my-nginx"
tags = ["latest", "1.0"]
\\\\}
\\\\}
VirtualBox Template
source "virtualbox-iso" "ubuntu" \\\\{
iso_url = "https://releases.ubuntu.com/22.04/ubuntu-22.04.1-desktop-amd64.iso"
iso_checksum = "sha256:10f19c5b2b8d6db711582e0e27f5116296c34fe4b313ba45f9b201a5007056cb"
guest_os_type = "Ubuntu_64"
disk_size = 40000
memory = 2048
cpus = 2
ssh_username = "packer"
ssh_password = "packer"
ssh_timeout = "20m"
boot_command = [
"<enter><wait><f6><wait><esc><wait>",
"<bs><bs><bs><bs><bs><bs><bs><bs><bs><bs>",
"<bs><bs><bs><bs><bs><bs><bs><bs><bs><bs>",
"<bs><bs><bs><bs><bs><bs><bs><bs><bs><bs>",
"<bs><bs><bs><bs><bs><bs><bs><bs><bs><bs>",
"<bs><bs><bs><bs><bs><bs><bs><bs><bs><bs>",
"<bs><bs><bs><bs><bs><bs><bs><bs><bs><bs>",
"<bs><bs><bs><bs><bs><bs><bs><bs><bs><bs>",
"<bs><bs><bs><bs><bs><bs><bs><bs><bs><bs>",
"<bs><bs><bs>",
"/install/vmlinuz",
" initrd=/install/initrd.gz",
" priority=critical",
" locale=en_US",
" file=/media/preseed.cfg",
"<enter>"
]
shutdown_command = "echo 'packer'|sudo -S shutdown -P now"
\\\\}
Provisioners
Shell Provisioner
provisioner "shell" \\\\{
inline = [
"sudo apt-get update",
"sudo apt-get install -y nginx"
]
\\\\}
provisioner "shell" \\\\{
script = "scripts/install-docker.sh"
\\\\}
provisioner "shell" \\\\{
scripts = [
"scripts/update-system.sh",
"scripts/install-apps.sh",
"scripts/configure-services.sh"
]
\\\\}
File Provisioner
provisioner "file" \\\\{
source = "files/"
destination = "/tmp/"
\\\\}
provisioner "file" \\\\{
content = "Hello World"
destination = "/tmp/hello.txt"
\\\\}
Ansible Provisioner
provisioner "ansible" \\\\{
playbook_file = "ansible/playbook.yml"
extra_arguments = [
"--extra-vars",
"ansible_ssh_user=ubuntu"
]
\\\\}
PowerShell Provisioner (Windows)
provisioner "powershell" \\\\{
inline = [
"Write-Host 'Installing IIS'",
"Enable-WindowsOptionalFeature -Online -FeatureName IIS-WebServerRole",
"Enable-WindowsOptionalFeature -Online -FeatureName IIS-WebServer"
]
\\\\}
Post-Processors
Docker Tag
post-processor "docker-tag" \\\\{
repository = "myapp"
tags = ["latest", "v1.0.0"]
\\\\}
Docker Push
post-processor "docker-push" \\\\{
login = true
login_username = var.docker_username
login_password = var.docker_password
\\\\}
Manifest
post-processor "manifest" \\\\{
output = "manifest.json"
strip_path = true
custom_data = \\\\{
build_time = timestamp()
version = var.app_version
\\\\}
\\\\}
Compress
post-processor "compress" \\\\{
output = "image.tar.gz"
\\\\}
Variables and Functions
Variable Definitions
variable "region" \\\\{
type = string
description = "AWS region"
default = "us-west-2"
\\\\}
variable "instance_type" \\\\{
type = string
validation \\\\{
condition = contains([
"t2.micro",
"t2.small",
"t2.medium"
], var.instance_type)
error_message = "Instance type must be t2.micro, t2.small, or t2.medium."
\\\\}
\\\\}
Local Values
locals \\\\{
timestamp = regex_replace(timestamp(), "[- TZ:]", "")
common_tags = \\\\{
Project = "MyProject"
Environment = "Production"
BuildTime = timestamp()
\\\\}
\\\\}
Functions
# String functions
ami_name = "myapp-$\\\\{formatdate("YYYY-MM-DD-hhmm", timestamp())\\\\}"
# File functions
user_data = base64encode(file("scripts/user-data.sh"))
# Collection functions
security_groups = concat(var.base_security_groups, var.additional_security_groups)
Parallel Builds
build \\\\{
sources = [
"source.amazon-ebs.ubuntu",
"source.azure-arm.ubuntu",
"source.googlecompute.ubuntu"
]
provisioner "shell" \\\\{
inline = [
"echo 'This runs on all platforms'"
]
\\\\}
\\\\}
provisioner "shell" \\\\{
only = ["amazon-ebs.ubuntu"]
inline = [
"echo 'AWS-specific configuration'"
]
\\\\}
provisioner "shell" \\\\{
except = ["virtualbox-iso.ubuntu"]
inline = [
"echo 'Cloud-specific configuration'"
]
\\\\}
Advanced Features
Conditional Builds
build \\\\{
sources = var.build_aws ? ["source.amazon-ebs.ubuntu"] : []
dynamic "provisioner" \\\\{
for_each = var.install_docker ? [1] : []
content \\\\{
shell \\\\{
inline = ["curl -fsSL https://get.docker.com|sh"]
\\\\}
\\\\}
\\\\}
\\\\}
Error Handling
provisioner "shell" \\\\{
inline = [
"sudo apt-get update||(sleep 30 && sudo apt-get update)"
]
max_retries = 3
pause_before = "10s"
\\\\}
Breakpoints for Debugging
provisioner "breakpoint" \\\\{
disable = false
note = "Debug point - check system state"
\\\\}
Best Practices
Template Organization
project/
├── templates/
│ ├── aws.pkr.hcl
│ ├── azure.pkr.hcl
│ └── variables.pkr.hcl
├── scripts/
│ ├── install-docker.sh
│ └── configure-nginx.sh
├── files/
│ └── nginx.conf
└── variables/
├── dev.pkrvars.hcl
└── prod.pkrvars.hcl
Security Best Practices
- Credentials: Use IAM roles instead of access keys
- Secrets: Store secrets in external systems (Vault, AWS Secrets Manager)
- Base Images: Use official, updated base images
- Scanning: Scan images for vulnerabilities
- Minimal Images: Install only necessary packages
- Parallel Builds: Build multiple platforms simultaneously
- Caching: Use package managers' caching features
- Layer Optimization: Minimize image layers
- Resource Sizing: Use appropriate instance sizes
- Network: Use fast network connections
Maintenance
- Version Control: Store templates in version control
- Testing: Test templates in CI/CD pipelines
- Documentation: Document template purpose and usage
- Updates: Regularly update base images and dependencies
- Monitoring: Monitor build times and success rates