I am trying to connect to an host which is nothing but an cisco ios switch which I get by executing an powershell script. So basically the switch is output from an xml string from an powershell script. I am able to successfully receive the switch name from Ansible output. Now my question is how do I connect to the switch and see the details of the switch using show commands.

This my playbook:

hosts: localhost
connection: local
  - name: Parse the XML output
      xmlstring: "{{ hostvars[groups['win'][0]]['splat']['stdout'] }}"
      xpath: "/HostDiscovery/Host/Connection/NetworkDevice[Candidate='true' and  Uplink='false']/DeviceName"
      content: text
    register: data
  - debug:
      msg: "{{ item.DeviceName }}"
    with_items: "{{ data.matches }}"

This will give an output as follows

TASK [debug]
task path: /etc/ansible/splat_executeps_script.yml:21 ok: [localhost] => (item={u'DeviceName': u'abc'}) => { "msg": "abc" }

where abc is the host to which I need to connect to in the subsequent task in the same playbook. I have tried writing something as below in the same yaml file

hosts: "{{ item.DeviceName }}"

connection: network_cli
  - name: Show VLAN
        - show vlan brief | include {{id}}
        - show interfaces {{interface}} status
    register: vlan
  - debug: var=vlan.stdout_lines
    with_items: "{{ data.matches }}"

But this does not run and gives the below error:

META: ran handlers ERROR! The field 'hosts' has an invalid value, which includes an undefined variable. The error was: 'item' is undefined

The error appears to have been in '/etc/ansible/splat_executeps_script.yml': line 27, column 3, but may be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

hosts: "{{ item.DeviceName }}" ^ here

How can I correct the details, any help would be appreciated? Please note that the device which I am trying to connect in the subsequent task would be dynamically generated by the xml which is returned from PS script.


item only exists for the duration of the loop in that task. Use variables that you have registered.

add_host is one way to dynamically modify inventory. Then run the next play in your playbook against that group:

  - name: Add discovered switches to inventory
      name: "{{ item.DeviceName }}"
      groups: switch
    loop: "{{ data.matches }}"

hosts: switch

To not have to manage the inventory every time in your playbook, write a dynamic inventory script or plugin. This could be a variation on that PowerShell script that emits JSON instead, which Ansible can use as an inventory script. Examples are in the Ansible source code, under contrib/inventory.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.