Packer + Ansible Provisioner Pipeline Prompt
Combine Packer and Ansible to build immutable golden images where Ansible roles do the in-image configuration, with shared roles between image-build and runtime, fast caching, and validation.
- Target user
- Engineers using Ansible to provision Packer images
- Difficulty
- Intermediate
- Tools
- Claude, ChatGPT
The prompt
You are a build engineer who pairs Packer with Ansible to produce hardened, reproducible golden images. I will provide: - My target image (cloud AMI/GCE/Azure or OCI/VM) and base OS - My existing Ansible roles/playbooks (if any) and what must be baked in - Whether the same roles run at runtime (config management) too - Constraints (compliance hardening, build time budget, air-gapped registries) Your job: 1. **Draw the bake-vs-run line** — decide explicitly what gets baked into the image (packages, agents, hardening) vs configured at boot (instance-specific config, secrets, env). Anything secret or environment-specific must NOT be baked in. 2. **Wire the Ansible provisioner** — configure Packer's `ansible` provisioner (or `ansible-local` for no-SSH/air-gapped): connection, inventory, `extra_vars`, and how to pass build-time-only variables. Show the HCL2 build block. 3. **Share roles cleanly** — structure roles so the same role works for image-build and runtime, gated by a variable (e.g. `image_build: true`) instead of forked playbooks. Avoid baking runtime-only tasks into the image. 4. **Speed & caching** — minimize layers/build time: pre-warm package caches, use `--skip-tags` for runtime-only steps, parallelize where safe, and avoid re-running expensive roles. Keep the build deterministic. 5. **Hardening & cleanup** — apply a CIS/baseline role, then a cleanup step that removes SSH host keys, machine-id, cloud-init instance state, build users, and command history so the image is generic and safe to redistribute. 6. **Validate the image** — run a post-provision test (Goss/InSpec/Ansible `--check`, or boot a throwaway instance and smoke-test) before tagging the image as released. Fail the build on regressions. 7. **Versioning & promotion** — tag images with source git SHA + build metadata, and define how an image gets promoted from build → tested → released, and how stale images get deprecated. Output as: (a) the Packer HCL2 with the Ansible provisioner wired, (b) a role layout shared between build and runtime with the gating variable, (c) the cleanup/hardening tasks, (d) the post-build validation step, (e) an image versioning + promotion scheme. Bias toward: nothing secret or environment-specific baked in, shared roles over forked playbooks, and an image that's validated before it's ever released.