Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 36 ยท Builders and Provisioners

Packer Ansible Provisioner and Other Configuration Tools

Configure images with the Packer ansible and ansible-local provisioners, PowerShell and Windows restarts, breakpoints, InSpec and Chef or Puppet, and learn when to use scripts or tools.

Shell scripts are fine for a few steps. As an image grows (users, packages, services, hardening, monitoring agents), scripts become long and fragile. A configuration management tool such as Ansible describes the desired state declaratively and handles ordering, idempotence and templating. Packer integrates with these tools through provisioners. This lesson covers the Ansible provisioners in detail, the Windows provisioners, the breakpoint debugging provisioner and the testing provisioner InSpec, and gives a rule for choosing.

Ansible, Windows machines and real Packer runs are not available on this site, so the examples are read-only and no tool output is shown. The Python stand-in assembles an ansible-playbook command line from provisioner settings to show how the pieces map; it is a model, not the plugin's code.

Two Ansible provisioners

ansible ansible-local
Where Ansible runs On your machine (or CI runner) Inside the image being built
What it needs Ansible installed where Packer runs Ansible installed in the image first
How it reaches the target Over SSH through a small proxy Packer opens Local connection, no SSH
Good for Normal Linux builds, Ansible stays out of the image Windows hosts without SSH from your side, or when the control machine cannot reach the VM

Both come from the ansible plugin:

HCL
packer {
  required_plugins {
    ansible = {
      version = "~> 1"
      source  = "github.com/hashicorp/ansible"
    }
  }
}

The ansible provisioner

HCL
build {
  sources = ["source.amazon-ebs.web"]

  provisioner "ansible" {
    playbook_file = "${path.root}/ansible/site.yml"
    user          = "ubuntu"

    extra_arguments = [
      "--extra-vars", "app_version=${var.app_version}",
    ]

    ansible_env_vars = [
      "ANSIBLE_HOST_KEY_CHECKING=False",
      "ANSIBLE_FORCE_COLOR=1",
    ]
  }
}

What Packer does:

  1. Waits until the machine is reachable.
  2. Writes a temporary inventory with one host (by default named default) and starts an SSH proxy (use_proxy = true) so Ansible connects through Packer's own authenticated channel. This avoids having to know the instance's key or IP.
  3. Runs ansible-playbook with that inventory, passing helpful extra variables such as packer_build_name and packer_builder_type.
  4. Fails the build if the playbook returns a non-zero exit code.

Other useful arguments: groups (put the host into inventory groups, so hosts: webservers matches), host_alias, galaxy_file plus roles_path (install roles), inventory_directory, use_proxy = false (connect directly to the machine's IP), command (custom ansible-playbook path) and ansible_ssh_extra_args.

A matching playbook:

YAML
# ansible/site.yml
- name: Configure web image
  hosts: default
  become: true
  tasks:
    - name: Install nginx
      ansible.builtin.apt:
        name: nginx
        state: present
        update_cache: true

    - name: Enable and start nginx
      ansible.builtin.service:
        name: nginx
        enabled: true

hosts must match what Packer puts in the inventory: default (the alias) or a group you configured with groups. become: true is needed for system changes because the SSH user is unprivileged.

Common problems

  • Ansible not found: install Ansible on the machine that runs Packer; on Windows run Packer from WSL.
  • Python missing on the target: Ansible modules need Python in the image; minimal images may need a first shell provisioner (sudo apt-get install -y python3).
  • Host key and SSH option errors: set ANSIBLE_HOST_KEY_CHECKING=False for the temporary host, and pass ansible_ssh_extra_args when newer OpenSSH versions reject old algorithms (read the error text; it names the setting).
  • Playbook works by hand but not in Packer: compare variables; Packer adds ansible_user and port values. Reproduce with -debug or run packer build with PACKER_LOG=1 and read the exact command line.

The ansible-local provisioner

HCL
provisioner "shell" {
  inline = ["sudo apt-get update", "sudo apt-get install -y ansible"]
}

provisioner "ansible-local" {
  playbook_file   = "${path.root}/ansible/site.yml"
  playbook_dir    = "${path.root}/ansible"     # uploaded together with roles and templates
  extra_arguments = ["--extra-vars", "env=${var.env}"]
}

Packer uploads the playbook (and playbook_dir) to the machine and runs ansible-playbook there against localhost. Use hosts: all or localhost in the playbook. Remember that Ansible stays in the image unless you remove it in a final cleanup step.

Idempotence

A good playbook can run twice without changing anything the second time. That matters for images because you rebuild them often, and it is the property you test by running the playbook in a container first. Use modules (apt, service, copy, template) rather than raw command tasks.

A command-line builder stand-in

This Python stand-in turns provisioner settings into an ansible-playbook command, so you can compare use_proxy modes. The flags are a simplified model chosen for teaching; consult the plugin documentation for the exact ones.

Python Stand-in: from settings to a command line

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Windows provisioners

Windows images use WinRM or OpenSSH as communicator and these provisioners:

HCL
provisioner "powershell" {
  inline = [
    "Install-WindowsFeature -Name Web-Server",
    "Write-Host 'IIS installed'",
  ]
}

provisioner "windows-restart" {
  restart_timeout = "15m"
}

provisioner "powershell" {
  script = "${path.root}/scripts/cleanup.ps1"
}

provisioner "windows-shell" {
  inline = ["dir C:\\"]
}

powershell runs PowerShell commands or scripts; windows-shell runs cmd.exe commands; windows-restart reboots and waits for the communicator to return, which is better than a manual shutdown /r. Windows images are finalised with Sysprep so each clone gets a new identity. Cloud builders (for example amazon-ebs) offer a user-data script that enables WinRM at boot.

breakpoint: stop and look around

HCL
provisioner "breakpoint" {
  note = "Check /etc/nginx before the image is saved"
}

The build pauses at this step until you press Enter, giving you time to SSH into the temporary machine. Remove it before running in CI (a paused CI job hangs until its timeout); alternatively use -debug locally.

Testing: InSpec and friends

An image is only useful if it matches its specification. The InSpec provisioner runs compliance profiles against the machine before it is saved:

HCL
provisioner "inspec" {
  profile = "${path.root}/tests/baseline"
  extra_arguments = ["--no-distinct-exit"]
}

If controls fail, the build fails and no image is produced. Alternatives: run Goss, Serverspec or your own test scripts via shell, or test after the build by launching the artifact (Testing and security chapter). Chef (chef-solo, chef-client) and Puppet (puppet-masterless, puppet-server) provisioners exist for teams already using those tools.

Choosing between scripts and tools

Situation Use
Five or fewer simple commands shell inline
Install-and-enable recipe, some templated files shell scripts plus file
Many packages, users, services, reusable roles Ansible (or Chef/Puppet if already standard)
Compliance requirement Add InSpec (or similar) as a test step
Windows powershell plus windows-restart; Ansible over WinRM if you already use it

Mixing is normal: bootstrap Python with shell, configure with ansible, tidy up with a final shell, test with inspec.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where does the ansible provisioner run Ansible?

    ansible runs locally and connects over SSH (usually via a Packer proxy); ansible-local runs inside the image.
  2. 2. Which host pattern in the playbook matches Packer's default inventory?

    The default host alias is default. With groups set, you can also match those group names.
  3. 3. Why is windows-restart preferable to running shutdown /r in a script?

    windows-restart handles the disconnect and waits for WinRM or SSH to return.
  4. 4. What does the breakpoint provisioner do?

    It is a debugging aid and should not be left in CI templates.
  5. 5. A playbook module fails with 'python not found' on a minimal image. What is the fix?

    Most Ansible modules run Python on the target, so it must exist before the playbook starts.

Summary

  • ansible runs Ansible on your machine through a temporary inventory and SSH proxy; ansible-local uploads the playbook and runs it inside the image.
  • Playbooks target the default host (or groups set in the provisioner) and need become for system changes; the target needs Python.
  • Windows uses powershell, windows-shell and windows-restart, plus Sysprep for the final image.
  • breakpoint pauses for inspection; inspec (and similar tools) can fail the build on non-compliant images.
  • Choose by size of the job: scripts for little, Ansible or similar for much, and always test.

Next: Input variables