Hello I need help with writing a play for finding all routers and switches in the network.
Environment:
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:
Thank you for your time.
What you are doing here is a programming. You are trying to write a program using a tool which is less suited for programming than any programming language out there. May be brainfuck is worse, but I'm not sure.
There is no good answer to your question on 'how to do this complicated business logic with Ansible', like there is no good answer on question 'how to tighten a nut with a hammer'.
What you need to do (either):
I advise you to go for No 1 or 2.