Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 36 ยท Testing and Security

Hardening and Securing Packer Images

Secure the image build: keep secrets out of images and logs, use sensitive variables and short-lived credentials, harden the OS, remove build leftovers and protect the pipeline.

An image is copied to every server that boots from it. A mistake in the image, such as a baked-in password, an old SSH key or an unpatched package, is therefore multiplied across the fleet. Security for Packer has two sides: the content of the image and the process that builds it. This lesson covers both.

Packer cannot run on this site. HCL and shell snippets are read-only; the JavaScript examples are stand-in scanners that practise the checks. The patterns shown are general guidance, not a complete compliance program.

Keep secrets out of the image

Anything written to the image's disk can be read by anyone who can launch it, copy the snapshot or read the AMI. Typical leaks:

  • A cloud access key or API token exported in a provisioner and left in shell history or a config file.
  • A private deploy key copied in with the file provisioner.
  • The temporary build user's password or SSH key.
  • .git folders and .env files copied from the build context.
  • Build logs under /var/log or /root containing tokens.

Practices that avoid them:

  1. Fetch secrets at runtime, not at build time. The image holds the means (an instance role, a secrets-manager agent) but not the secret.
  2. Use short-lived credentials for the build itself. In CI, use OIDC federation or an assumed role, not a stored access key.
  3. If a provisioner needs a token, delete it afterwards and clear shell history: history -c, remove ~/.bash_history, remove files under /tmp.
  4. Use sensitive = true on variables so Packer hides their values in output.
  5. Scan the finished image for secrets (for example with a secret scanner over the mounted filesystem) as a pipeline step.
HCL
variable "api_token" {
  type      = string
  sensitive = true
  default   = env("API_TOKEN")
}

Setting sensitive redacts the value in Packer's UI output, but it does not prevent your own script from writing it to disk or to a log, and PACKER_LOG=1 may still reveal request details. Treat logs as sensitive.

Clean up the machine

A final provisioner (the "cleanup" step) should remove what the build used:

Terminal
sudo apt-get clean
sudo rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
sudo truncate -s 0 /etc/machine-id          # new ID per instance
sudo rm -f /etc/ssh/ssh_host_*              # regenerate host keys on first boot
sudo cloud-init clean --logs                # let cloud-init run again at launch
sudo rm -f /root/.bash_history /home/*/.bash_history

Regenerating SSH host keys and the machine id matters: otherwise every clone shares the same identity. Check how your OS and cloud-init regenerate them before deleting.

Harden the operating system

Start with a minimal, trusted base (official image or your own hardened parent). Then:

  • Apply updates during the build and rebuild regularly (rebuild schedules).
  • Remove software you do not need; a smaller image has fewer vulnerabilities.
  • Disable password SSH login and root login; use keys or the cloud's identity-aware access.
  • Enable a host firewall default-deny where practical, and the audit daemon and time sync.
  • Apply a benchmark such as CIS or a vendor STIG with an automated role (Ansible, a script) and verify it with InSpec or OpenSCAP.
  • Set file permissions, sysctl hardening, and disable unused filesystems and protocols.
  • On AWS, require IMDSv2 and encrypt volumes; on all clouds, create the image in a private network where possible.

Protect the supply chain

  • Pin and verify downloads: use checksums or signatures for every binary a provisioner fetches; do not curl | sh unpinned scripts.
  • Pin plugin versions in required_plugins and review upgrades.
  • Trust the parent image. Filter by owner and prefer images you built and signed.
  • Restrict who can build and publish. The pipeline role should have just enough permissions (launch instance, create image, tag), and image sharing should be explicit.
  • Record provenance: commit SHA, pipeline run, base image id in tags and the manifest (manifest lesson), so any running server can be traced back to its source.
  • Sign and attest artifacts when your platform supports it (for example container image signatures or build provenance).
flowchart TD
  S["Trusted base + pinned downloads"] --> B["Build in private network, short-lived creds"]
  B --> H["Harden + clean up"]
  H --> V["Scan + test"]
  V --> P["Sign, tag, record provenance"]

Try it: scan files for secrets

JS Secret scanner (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The keys and tokens in this sample are fake placeholders.

Try it: a hardening checklist

JS SSH config check (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does sensitive = true on a Packer variable do?

    It redacts output but cannot protect secrets you write to disk or logs.
  2. 2. Why remove /etc/ssh/ssh_host_* and truncate /etc/machine-id before capture?

    Shared host keys and machine ids across clones are a security and operations problem.
  3. 3. What is the best way to provide a database password to servers launched from the image?

    Secrets baked into images can be read by anyone with access to the image.
  4. 4. Which practice protects against tampered downloads in provisioners?

    Pinned, verified inputs keep the image reproducible and trustworthy.

Summary

  • Never bake secrets into an image; fetch them at runtime and use short-lived credentials for the build.
  • Clean temporary users, keys, histories and identities before the snapshot.
  • Harden against a benchmark and verify it automatically.
  • Pin and verify inputs, restrict who can publish, and record provenance.

Next: Packer in GitHub Actions