Skip to content

Packer

Comprehensive HashiCorp Packer commands and workflows for automated machine image building across multiple platforms.

Installation & Setup

CommandDescription
packer versionShow Packer version
packer -helpShow help information
packer -help buildShow help for specific command

Core Commands

Build Operations

CommandDescription
packer build template.pkr.hclBuild image from template
packer build -var 'region=us-west-2' template.pkr.hclBuild with variables
packer build -var-file=vars.pkrvars.hcl template.pkr.hclBuild with variable file
packer build -only=amazon-ebs template.pkr.hclBuild specific builder only
packer build -except=virtualbox-iso template.pkr.hclExclude specific builder

Validation and Inspection

CommandDescription
packer validate template.pkr.hclValidate template
packer inspect template.pkr.hclInspect template
packer fmt template.pkr.hclFormat template
packer fmt -diff template.pkr.hclShow formatting differences

Plugin Management

CommandDescription
packer init template.pkr.hclInitialize and install plugins
packer plugins install github.com/hashicorp/amazonInstall specific plugin
packer plugins installedList installed plugins

Template Examples

AWS AMI Template

hcl
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

hcl
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

hcl
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

hcl
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

hcl
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

hcl
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

hcl
provisioner "file" {
  source      = "files/"
  destination = "/tmp/"
}

provisioner "file" {
  content     = "Hello World"
  destination = "/tmp/hello.txt"
}

Ansible Provisioner

hcl
provisioner "ansible" {
  playbook_file = "ansible/playbook.yml"
  
  extra_arguments = [
    "--extra-vars",
    "ansible_ssh_user=ubuntu"
  ]
}

PowerShell Provisioner (Windows)

hcl
provisioner "powershell" {
  inline = [
    "Write-Host 'Installing IIS'",
    "Enable-WindowsOptionalFeature -Online -FeatureName IIS-WebServerRole",
    "Enable-WindowsOptionalFeature -Online -FeatureName IIS-WebServer"
  ]
}

Post-Processors

Docker Tag

hcl
post-processor "docker-tag" {
  repository = "myapp"
  tags       = ["latest", "v1.0.0"]
}

Docker Push

hcl
post-processor "docker-push" {
  login          = true
  login_username = var.docker_username
  login_password = var.docker_password
}

Manifest

hcl
post-processor "manifest" {
  output = "manifest.json"
  strip_path = true
  custom_data = {
    build_time = timestamp()
    version    = var.app_version
  }
}

Compress

hcl
post-processor "compress" {
  output = "image.tar.gz"
}

Variables and Functions

Variable Definitions

hcl
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

hcl
locals {
  timestamp = regex_replace(timestamp(), "[- TZ:]", "")
  
  common_tags = {
    Project     = "MyProject"
    Environment = "Production"
    BuildTime   = timestamp()
  }
}

Functions

hcl
# 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)

Multi-Platform Builds

Parallel Builds

hcl
build {
  sources = [
    "source.amazon-ebs.ubuntu",
    "source.azure-arm.ubuntu",
    "source.googlecompute.ubuntu"
  ]
  
  provisioner "shell" {
    inline = [
      "echo 'This runs on all platforms'"
    ]
  }
}

Platform-Specific Provisioning

hcl
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

hcl
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

hcl
provisioner "shell" {
  inline = [
    "sudo apt-get update || (sleep 30 && sudo apt-get update)"
  ]
  
  max_retries = 3
  pause_before = "10s"
}

Breakpoints for Debugging

hcl
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

  1. Credentials: Use IAM roles instead of access keys
  2. Secrets: Store secrets in external systems (Vault, AWS Secrets Manager)
  3. Base Images: Use official, updated base images
  4. Scanning: Scan images for vulnerabilities
  5. Minimal Images: Install only necessary packages

Performance Optimization

  1. Parallel Builds: Build multiple platforms simultaneously
  2. Caching: Use package managers' caching features
  3. Layer Optimization: Minimize image layers
  4. Resource Sizing: Use appropriate instance sizes
  5. Network: Use fast network connections

Maintenance

  1. Version Control: Store templates in version control
  2. Testing: Test templates in CI/CD pipelines
  3. Documentation: Document template purpose and usage
  4. Updates: Regularly update base images and dependencies
  5. Monitoring: Monitor build times and success rates