packer build: Usage, Options & Common CI Errors
Build identical machine images for multiple platforms from one template.
packer build runs the builders and provisioners in a template to produce machine images (AMIs, Docker images, VM images). In CI it runs unattended with variables and cloud credentials.
What it does
packer build parses an HCL2 (.pkr.hcl) or JSON template, runs each builder to create a base machine, applies provisioners (shell, Ansible, file), then snapshots the result as an image and runs any post-processors. It is non-interactive by default and reports the artifact IDs at the end.
Common usage
# Build all sources in a template directory
packer build .
# Build a specific source only, with variables
packer build -only='amazon-ebs.ubuntu' -var 'region=us-east-1' template.pkr.hcl
# CI: load vars from a file, fail on the first error
packer build -var-file=ci.pkrvars.hcl .Common error in CI: plugins not installed / no credentials
build fails with "Error: Failed to initialize build ... required_plugins ... run 'packer init'" or with cloud auth errors like "NoCredentialProviders". Fix: run packer init . before build so required plugins are installed (HCL2 templates do not auto-install on build), and give the runner real cloud credentials (e.g. an AWS role / AWS_REGION). Pin plugin versions in the required_plugins block so CI is reproducible.
Key options
| Option | Purpose |
|---|---|
| -only=SRC | Build only matching sources |
| -except=SRC | Skip matching sources |
| -var KEY=VAL | Set a variable |
| -var-file=FILE | Load variables from a file |
| -force | Overwrite an existing artifact |
| -on-error=cleanup | Behavior when a build fails |