Search code examples
ansiblepacker

Passing a variable from Packer into Ansible


I would like to take a variable that's defined in a variable file in packer and pass it into Ansible. The ask is really quite simple, in the variable file I define a number of items. This ask I am trying to pass the vm_name into Ansible so I can run a playbook to rename the Windows Computer name to match the VM name.

In the variables.pkr.hcl file I have the following. This is just a snip.

vm_name                         = "Pod-1-RDS-01"
vm_version                      = 16

In the packer windows.pkr.hcl the vm name is set to use "var.vm_name"

    extra_arguments = [
      "--connection", "winrm",
      "--extra-vars", "ansible_shell_type=powershell ansible_shell_executable=None", "'vm_name=${var.vm_name}'"]

I run the following to build the VM. packer build -force -on-error=ask -var-file variables.pkr.hcl windows.pkr.hcl

This all works until I added the vm_name to the extra_arguments

enter image description here

I am hoping to pass the var.vm_name variable from packer into Ansible so that I can run this in the playbook and rename the Computer name to match the VM name.

  tasks:
    - name: Change the hostname 'var.vm_name'
      ansible.windows.win_hostname:
        name: 'var.vm_name'
        register: res
    - name: Reboot
      ansible.windows.win_reboot:
        when: res.reboot_required

Solution

  • You have to correct the way you pass a variable to Ansible and how you read the variables inside the playbook.

        extra_arguments = [
          "--connection", "winrm",
          "--extra-vars", "ansible_shell_type=powershell ansible_shell_executable=None vm_name=${var.vm_name}"]
    
    

    I personally prefer this way because it is more readable for me:

        extra_arguments = [
          "--connection", "winrm",
          "--extra-vars", "ansible_shell_type=powershell",
          "--extra-vars", "ansible_shell_executable=None",
          "--extra-vars", "vm_name=${var.vm_name}"
        ]
    

    You can find more examples in Ansible provisioner documentation https://developer.hashicorp.com/packer/plugins/provisioners/ansible/ansible

    If you want to use vm_name inside Ansible playbook lets try this:

      tasks:
        - name: Change the hostname 'var.vm_name'
          ansible.windows.win_hostname:
            name: "{{ vm_name }}"
            register: res
        - name: Reboot
          ansible.windows.win_reboot:
            when: res.reboot_required
    

    https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_variables.html#referencing-simple-variables