ansibleansible-awxansible-tower

Ansible Tower how to pass inventory to my playbook variables


I am setting up a vmware job in Ansible Tower to snapshot a list of VM's, ideally, this list should be generated by AWX/Tower from the vSphere dynamic inventory. Inventory is named "lab_vm" in AWX and use either the hostname or the UUID of the VM.

How do I pass this through in my playbook variables file?

---
vars:
  vmware:
    host: '{{ lookup("env", "VMWARE_HOST") }}'
    username: '{{ lookup("env", "VMWARE_USER") }}'
    password: '{{ lookup("env", "VMWARE_PASSWORD") }}'
  vcenter_datacenter: "dc1"
  vcenter_validate_certs: false
  vm_name: "EVE-NG"
  vm_template: "Win2019-Template"
  vm_folder: "Network Labs"

my playbook

---
- name: vm snapshot
  hosts: localhost
  become: false
  gather_facts: false
  collections:
    - community.vmware
  pre_tasks:
    - include_vars: vars.yml
  tasks:
    - name: create snapshot
      vmware_guest_snapshot:
#        hostname: "{{ host }}"
#        username: "{{ user }}"
#        password: "{{ password }}"
        datacenter: "{{ vcenter_datacenter }}"
        validate_certs: False
        name: "{{ vm_name }}"
        state: present
        snapshot_name: "Ansible Managed Snapshot"
        folder: "{{ vm_folder }}"
        description: "This snapshot is created by Ansible Playbook"

Solution

  • You're going about it backward. Ansible loops through the inventory for you. Use that feature, and delegate the task to localhost:

    ---
    - name: vm snapshot
      hosts: all
      become: false
      gather_facts: false
      collections:
        - community.vmware
      pre_tasks:
        - include_vars: vars.yml
      tasks:
        - name: create snapshot
          vmware_guest_snapshot:
            datacenter: "{{ vcenter_datacenter }}"
            validate_certs: False
            name: "{{ inventory_hostname }}"
            state: present
            snapshot_name: "Ansible Managed Snapshot"
            folder: "{{ vm_folder }}"
            description: "This snapshot is created by Ansible Playbook"
          delegate_to: localhost
    

    I've not used this particular module before, but don't your want snapshot_name to be unique for each guest?