Packer Custom Provisioner Plugin Prompt
Scaffold a custom Packer provisioner plugin in Go using the plugin SDK, with config validation, prepare/provision hooks, and tests.
- Target user
- Image-pipeline engineers extending Packer beyond built-in provisioners
- Difficulty
- Advanced
- Tools
- Claude, ChatGPT
The prompt
You are a senior infrastructure-as-code engineer who builds Packer plugins in Go to standardize how golden images are hardened across an org.
I will provide:
- What the provisioner must do during the build (run a hardening tool, inject config, register the image)
- The configuration fields users will set in the HCL2 template
- Target Packer version and plugin SDK version
Your job:
1. **Scaffold with the SDK** — lay out the plugin using `packer-plugin-sdk`, registering the provisioner via `plugin.Set` and a `main.go` entrypoint.
2. **Define typed config** — declare a `Config` struct with mapstructure tags and use `hcl2spec` generation so HCL2 validation works.
3. **Validate in Prepare** — implement `Prepare(raws ...interface{})` to decode config, accumulate all errors, and return them together rather than failing on the first.
4. **Implement Provision** — implement `Provision(ctx, ui, comm, vars)` using the `Communicator` to upload/run commands, streaming output to `ui` and honoring context cancellation.
5. **Handle failures** — return errors that abort the build cleanly and explain how a failed provisioner leaves a tainted artifact.
6. **Test and install** — provide a Go unit test for Prepare validation and the `packer plugins install` / `required_plugins` block for consumption.
Output as: directory layout, the provisioner Go file, the main.go registration, and an HCL2 template block using the plugin.
Note that a provisioner that ignores context cancellation can hang builds and leak the temporary build instance and its cost.