首页 > 解决方案 > 使用 CDP 邻居映射网络中所有路由器和交换机的 Ansible 剧本

问题描述

您好,我需要帮助编写一个查找网络中所有路由器和交换机的剧本。

环境:

问题陈述:

从核心交换机开始,使用 cdp 邻居遍历所有路径,直到域内的最后一个交换机/路由器。网络的深度未知。

输出:JSON 包含网络设备的分层排序。

{

答:{A1,A2},

C:{C1,C5:{C5i:{..},C5j}

}

我的尝试:

---
- 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

我之前使用 netmiko 在 python 中编写了这个脚本,但现在我们需要用 Ansible 编写它。

问题:

感谢您的时间。

标签: automationansiblecisco-iosansible-awx

解决方案


你在这里做的是编程。您正在尝试使用一种比其他任何编程语言都更不适合编程的工具来编写程序。可能是brainfuck更糟,但我不确定。

关于“如何使用 Ansible 执行这种复杂的业务逻辑”的问题没有很好的答案,就像关于“如何用锤子拧紧螺母”的问题没有很好的答案一样。

你需要做什么(或者):

  1. 编写一个独立的应用程序并将其与 Ansible 结合使用(通过 rest API、库存、stdin/out 等等)
  2. 为 Ansible 编写一个模块。你在标准输入上得到了 json,你在标准输出上用 json 回答。Python 有 ansible hepler,但是你可以自由地使用任何语言作为模块。
  3. 为 Ansible 编写一个查找插件。这更加棘手,您需要随着 Ansible 的发展保持其运行。

我建议你选择 1 号或 2 号。


推荐阅读