Hello I need help with writing a play for finding all routers and switches in the network.
Environment:
- Ansible 2.8
- Python 2.7
- Test network in eve-ng
- Router and Switches have ios
Problem Statement:
Start at the core switch and by using cdp neighbors traverse all the paths till the last switch/router inside the domain. The depth of the network is unknown.
Output: JSON containing a hierarchical ordering of network devices.
{
A:{A1,A2},
C:{C1,C5:{C5i:{..},C5j}
}
My Attempt:
---
- name: Backup show run (enable mode commands)
hosts: ["testrouter"]
gather_facts: false
connection: network_cli
vars:
ansible_network_os: ios
grand_parent: ["testrouter"]
tasks:
- name: CDP for "{{ inventory_hostname }}"
register: all_facts
ios_facts:
gather_subset: all
- name: filter cdp neighbors for all facts
debug:
msg: "Child of {{ inventory_hostname }} is {{ item.value[0].host }}"
loop: "{{ lookup('dict', all_facts.ansible_facts.ansible_net_neighbors) }}"
when: item.value|length == 1
- name: Remove previous grand_parent
set_fact:
root: "['{{ parent[0] }}']"
when: parent|length == 2
- name: Add the latest host as grand_parent
set_fact:
root: "{{ parent + [ inventory_hostname ] }}"
when: parent|length == 1
I have written this script in python using netmiko previously but now we have a requirement for it to be written in Ansible.
Problems:
- I don't know how to modify hosts dynamically as I discovery new hosts with cdp neighbors.
- Plus I need recursion to explore to unknown depth
- Also since, I am learning Ansible for first time I am worried I would over complicate things and write bloated code.
Thank you for your time.