Ansible 行动手册,用于使用 CDP 邻居映射网络中的所有路由器和交换机



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

环境:

  • 安斯布尔 2.8
  • 蟒蛇 2.7
  • 前夕的测试网络
  • 路由器和交换机具有ios

问题陈述:

从核心交换机开始,并使用 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 编写它。

问题:

  • 我不知道如何在发现具有cdp邻居的新主机时动态修改主机。
  • 另外,我需要递归来探索未知的深度
  • 同样从那以后,我第一次学习 Ansible,我担心我会让事情过于复杂并编写臃肿的代码。

谢谢你的时间。

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

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

您需要做什么(任一项(:

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

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

最新更新