Search code examples
automationansiblecisco-iosansible-awx

Ansible playbook for Mapping all Routers and Switches in the network using CDP Neighbor


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.


Solution

  • 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):

    1. Write an stand-alone application and use it in conjunction with Ansible (via rest API, inventory, stdin/out, you name it)
    2. Write a module for Ansible. You got json at stdin, you answer with json on stdout. There are ansible heplers for Python, but you are free to use any language for module.
    3. Write a lookup plugin for Ansible. This is more tricky and you need to keep it operational as Ansible evolves.

    I advise you to go for No 1 or 2.