listansiblepacker

How to set a variable as a list in Packer for Ansible?


When trying to pass a var that is normally a list in Ansible, I cannot do this in packer.

  provisioner "ansible" {
    playbook_file = "./ansible/houdini_module.yaml"
    extra_arguments = [
      "-vv",
      "--extra-vars",
      "houdini_major_version_list=[19.0]",
    ]
  }

In my playbook if I test the length of houdini_major_version_list with {{ houdini_major_version_list|length }} it says the length is 6, when it should be 1.

What is the correct way to pass a list using --extra-vars in packer?


Solution

  • The other answer is instructive in explaining why the type is incorrect as a variable input to Ansible through the CLI. The update to the Packer HCL2 template to satisfy this requirement and solve your problem would be:

    provisioner "ansible" {
      playbook_file = "${path.root}/ansible/playbook.yaml"
      extra_arguments = [
        "-vv",
        "--extra-vars",
        jsonencode({ "houdini_major_version_list" = ["19.0"] }),
      ]
    }
    

    setting the env var PACKER_LOG=1 we see that this executes:

    ansible-playbook ... -vv --extra-vars {"houdini_major_version_list":["19.0"]} ... /path/to/playbook.yaml
    

    This demonstrates the interfacing between Packer and the Ansible provisioner is now correct for passing a list type variable.

    Note that jsonencode({ "houdini_major_version_list" = [19.0] results in {"houdini_major_version_list":[19]} because the float automatically drops the .0.