ansible - 寻求帮助过滤 ansible stdout_lines
问题描述
我有一组交换机,用户一直要求我找到 mac 地址,以便追踪确切的端口并将该端口编辑到新的 vlan。我没有登录每个交换机并跟踪 mac 所在的交换机,而是创建了一个 ansible 一个基本的 ansible playbook 来帮助我解决这个问题:
---
- name: Find mac address in sec-switches
hosts: sec-switch
gather_facts: false
connection: local
vars_prompt:
- name: mac
prompt: What is the mac address?
private: no
tasks:
-
name: debugging
ansible.builtin.debug:
msg: 'Searching for {{ mac }}'
-
name: "search"
register: output
ios_command:
commands:
- "show mac address-table | include {{ mac }}"
-
debug: var=output.stdout_lines
运行时,我的调试给了我:(片段)
}
ok: [10.1.1.32] => {
"output.stdout_lines": [
[
"24 0050.f967.5cb7 DYNAMIC Gi1/0/48"
]
]
}
ok: [10.1.1.33] => {
"output.stdout_lines": [
[
"24 0050.f967.5cb7 DYNAMIC Gi1/0/48"
]
]
}
ok: [10.1.1.30] => {
"output.stdout_lines": [
[
"4 0050.f967.5cb7 DYNAMIC Gi1/1/1",
" 24 0050.f967.5cb7 DYNAMIC Gi1/1/1"
]
]
}
我想过滤输出并为每个开关运行 sh 接口描述 | inc {使用返回的接口}。这样我可以排除上行链路。
IE:在交换机 10.1.1.33 上我运行:sh 接口描述 | inc Gi1/0/48 并返回: Gi1/0/48 up up UPLINK
这让我知道我不需要担心那个开关是上行链路。
所以我想知道是否有办法过滤 output.stdout_lines 的输出,只显示输出的第 4 个条目:所以对于这个输出:“24 0050.f967.5cb7 DYNAMIC Gi1/0/48”有没有它只显示的方式:“Gi1/0/48”如果它可以做到这一点,我可以将其设置为事实并运行:ios_command:commands:-“show sh interfaces description | inc {{registered fact}}”
任何帮助,将不胜感激。我查看了https://docs.ansible.com/ansible/latest/user_guide/playbooks_filters.html
提前致谢。
解决方案
最后一块拼图来自 rajthecomputerguy:
使用 strip() 方法去除空白
debug:
var: intf[0].strip()
完整代码:
---
- name: Find mac address in sec-switches
hosts: sec-switch
gather_facts: false
connection: local
vars_prompt:
- name: mac
prompt: What is the mac address?
private: no
tasks:
-
name: debugging
ansible.builtin.debug:
msg: 'Searching for {{ mac }}'
-
name: search
ios_command:
commands:
- "show mac address-table | include {{ mac }}"
register: printout
- set_fact:
intf: |
{{printout.stdout_lines[0] |
map('regex_replace','^(?:[^ ]*\ ){12}([^ ]*)') |
list }}
-
name: show int desc
ios_command:
commands:
- "sh interfaces description | inc {{ intf[0].strip() }}"
register: printout2
- name: View output
debug:
var: printout2
推荐阅读
- javascript - Javascript window.print() 方法只工作一次
- python - 如何实现获取参数列表或元组列表的代码?
- elasticsearch - 我们如何进行关键不敏感基数聚合?
- java - 在 recyclerview 中调用 textview 和 imageview
- python - numpy 数组:在作为输入的一组行和列的固定窗口内计算 argmax 的有效方法
- aws-lambda - 使用 AWS lambda 步骤调用 java -jar 命令
- asp.net - ASP.NET Core:没有看到详细的错误,即使环境变量设置为开发
- arrays - 在字典中添加新键?
- c - 关于 C 中函数参数中的静态值
- typescript - 哪些方法遍历 Typescript AST 会产生什么结果?