Search code examples
python-2.7ciscoansible-facts

Searching Ansible debug messages for a string


I'm trying to find all the up interfaces on a switch, by looking at the results of some output from nxos_facts:

 - name: get nxos facts via nxapi
  nxos_facts:
    provider: "{{ provider['nxapi'] }}"
    gather_subset:
      - "interfaces"

  register: nxfacts_nxapi

- debug: 
    msg: "{{ nxfacts_nxapi.ansible_facts.ansible_net_interfaces | to_nice_json}} "

And I can successfully print out the debug to show the structure of the dictionary:

"ansible_net_interfaces": {
        "Ethernet1/1": {
            "bandwidth": 1000000,
            "duplex": "full",
            "ipv4": {
                "address": "10.0.1.2",
                "masklen": 24
            },
            "macaddress": "0800.276d.ee15",
            "mtu": "1500",
            "speed": "1000 Mb/s",
            "state": "up",
            "type": "100/1000/10000 Ethernet"
        },
        "Ethernet1/10": {
            "bandwidth": 10000000,
            "duplex": "auto",
            "macaddress": "0800.276c.eecc",
            "mode": "access",
            "mtu": "1500",
            "speed": "auto-speed",
            "state": "down",
            "type": "100/1000/10000 Ethernet"
        },

But I'm struggling with the syntax to dereference the dictionary to only print when the "state" is "up"?

I'm running with the following version:

ansible 2.3.1.0

Any help is much appreciated.


Solution

  • You can iterate over the dictionary of interfaces and print only those elements for which the condition is true. Example:

    - name: mytask
      debug:
        msg: "{{ item }}"
      when: "item.value.state == 'up'"
      with_dict: "{{ nxfacts_nxapi.ansible_facts.ansible_net_interfaces }}"