automation - 使用 CDP 邻居映射网络中所有路由器和交换机的 Ansible 剧本
问题描述
您好,我需要帮助编写一个查找网络中所有路由器和交换机的剧本。
环境:
- Ansible 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,所以我担心我会把事情复杂化并写出臃肿的代码。
感谢您的时间。
解决方案
你在这里做的是编程。您正在尝试使用一种比其他任何编程语言都更不适合编程的工具来编写程序。可能是brainfuck更糟,但我不确定。
关于“如何使用 Ansible 执行这种复杂的业务逻辑”的问题没有很好的答案,就像关于“如何用锤子拧紧螺母”的问题没有很好的答案一样。
你需要做什么(或者):
- 编写一个独立的应用程序并将其与 Ansible 结合使用(通过 rest API、库存、stdin/out 等等)
- 为 Ansible 编写一个模块。你在标准输入上得到了 json,你在标准输出上用 json 回答。Python 有 ansible hepler,但是你可以自由地使用任何语言作为模块。
- 为 Ansible 编写一个查找插件。这更加棘手,您需要随着 Ansible 的发展保持其运行。
我建议你选择 1 号或 2 号。
推荐阅读
- javascript - 向 Gutenberg 封面块添加额外的设置字段
- java - Flutter,访问隐藏方法
- html - 如何使同一行中的所有图像根据父 div 缩放?
- terraform - 地形版本.tf
- reactjs - .toBe 不是函数
- c# - 尝试实现登录时出现 ArgumentException(ASP.NET Core 项目)
- ruby-on-rails - 在 ruby on rails 中的 simple_form 中提供无效输入时显示验证错误消息
- azure-devops - 如何在 azure 管道的自定义 task.json 输入选项中填充动态数据
- intellij-idea - IntelliJ 删除具有相同“名称”的代码
- jquery - Jquery 滚动慢锚回到标题