Issue with Ansible wait_for module – how to reliably check if the VM is up and running

ansibleansible-playbook

I am trying to develop a simple playbook (which would later be used in larger ones) to check if Windows VMs in the inventory are up and running. I use Ansible Tower (free version) to manage the dynamic VMware inventory containing Windows VMs. These VMs are pre-configured to work with Ansible (winrm enabling etc.) Therefore, I don't maintain any manually edited hosts files.

- name: Check if VMs are up and running
  hosts: localhost

  tasks:
    - name: Pauses the workflow
      pause: minutes=5

    - name: Wait for port number 5986 to be available
      vars:
        - vmname: ['VM-NO1', 'VM-NO2']
      local_action: wait_for host={{ hostvars[item].ansible_ssh_host }} state=started delay=10 timeout=15 connect_timeout=15
      with_items: "{{ vmname }}"

I have the pause to provide some time for the VM to boot wherein I have tried times ranging from 1 to 5 minutes. The VMs come up in less than 3 minutes, actually.

I am facing a strange issue w.r.t. wait_for. While the VMs are up and running as can be seen from the vCenter Console, Ansible reports this failure:

fatal: [localhost]: FAILED! => {"failed": true, "msg": "the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'dict object' has no attribute 'ansible_ssh_host'\n\nThe error appears to have been in '/var/lib/awx/projects/vms/waitcheck.yml': line 10, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n – name: Wait for port number 5986 to be available\n ^ here\n"}

I have added and removed port=5986 flag in the wait_for section. Surprisingly, the same playbook runs and reports a success when running for the second time. How can I resolve this?

Best Answer

Ansible 2.3

  tasks:
    - name: Pauses the workflow
      pause: minutes=5

    - name: Wait for port number 5986 to be available
      wait_for:
        host: {{ hostvars[item]['ansible_host'] }}
        port: 5986
        delay: 10
        state: started
      with_items:
        - VM-NO1
        - VM-NO2
      delegate_to: 127.0.0.1