在搜索帮助过滤可行的stdout_lines



我有一组交换机,用户一直要求我找到mac地址,以便追踪确切的端口并将该端口编辑为新的vlan。我没有登录到每个交换机,然后追踪mac所在的交换机,而是创建了一个基本的脚本来帮助我:

---
- 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: On switch 10.1.1.33 I ran: sh interfaces description | inc Gi1/0/48返回:Gi1/0/48 up up UPLINK

这让我知道我不需要担心那个交换机,因为它是上行链路。

所以我想知道是否有一种方法来过滤输出的输出。Stdout_lines只显示输出的第4个条目:所以对于这个输出:24 0050.f967.5cb7 DYNAMIC Gi1/0/48"有没有办法让它显示:"Gi1/0/48"如果它能做到这一点,我能不能把它设为事实,然后运行:ios_command:命令:- "show sh接口描述| inc{{注册事实}}">

任何帮助都会很感激。我查看了https://docs.ansible.com/ansible/latest/user_guide/playbooks_filters.html

提前感谢。

最后一块拼图来自rajtheccomputerguy:

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

最新更新