Hawkeye Parker
Hawkeye Parker

Reputation: 8600

Ansible playbook - how to code nested for loop with multiple if conditions?

Here's the Python code -- I want to "write this same code" (get the same result) in my Ansible playbook in YAML and/or Jinja2, without needing to use an external module.

arp_interfaces = {
    "3.3.3.3": "eth0",
    "4.4.4.4": "eth1",
}

route_interfaces = [
    {
        "interface": "eth0",
        "next_hop_ip": "3.3.3.3",
        "unreachable": ""
    },
    {
        "interface": "eth2",
        "next_hop_ip": "4.4.4.4",
        "unreachable": ""
    }
]

different_interfaces = {}
for arp_ip, arp_iface in arp_interfaces.items():
    for route in route_interfaces:
        if arp_ip == route['next_hop_ip']:
            if arp_iface != route['interface']:
                different_interfaces[arp_ip] = {"arp": arp_iface, "ip_route": route["interface"]}

print(different_interfaces)

Output:

C:\Python373\python.exe D:/projects/Python/python-cli/main.py
{'4.4.4.4': {'arp': 'eth1', 'ip_route': 'eth2'}}

Upvotes: 1

Views: 60

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68004

The tasks below

- set_fact:
    different_interfaces: "{{ different_interfaces|default({})|
                              combine({item.0.key: {'arp': item.0.value,
                                                    'ip_route': item.1.interface}})
                              }}"
  loop: "{{ arp_interfaces|dict2items|product(route_interfaces)|list }}"
  when:
    - item.0.key == item.1.next_hop_ip
    - item.0.value != item.1.interface
- debug:
    var: different_interfaces

give

"different_interfaces": {
    "4.4.4.4": {
        "arp": "eth1", 
        "ip_route": "eth2"
    }
}

Upvotes: 1

Related Questions