Ansible Playbook处理Cisco IOS交换机CDP接口多余字符问题
解决Cisco IOS交换机CDP接口提取多余字符问题
问题根源
你的connecting_interface变量出现多余的['和, ",是因为stdout_lines[0]的原始输出包含额外格式字符,单纯替换前缀后缀无法彻底清理。最可靠的方式是直接匹配并提取符合Cisco接口命名规则的字符串。
修改后的Playbook
--- - name: Cisco Show CDP Neighbors hosts: switches gather_facts: false tasks: - name: Show CDP Interface ios_command: commands: sh cdp neighbors detail | i Interface register: interface - name: Extract CDP Interface set_fact: # 用regex_findall匹配接口名格式(字母+斜杠+数字),取第一个匹配结果 connecting_interface: "{{ interface.stdout_lines[0] | regex_findall('\\w+\\/\\d+\\/\\d+') | first }}" - name: Print Connecting Interface debug: var: connecting_interface
替代方案(适配更多接口格式)
如果接口名包含TenGigabit、FastEthernet等更长前缀,也可以通过精准截断实现:
- name: Extract CDP Interface set_fact: connecting_interface: "{{ interface.stdout_lines[0] | regex_replace('^.*Interface: ', '') | regex_replace(',.*$', '') }}"
这个逻辑是:
- 移除从开头到
Interface:的所有内容 - 移除从逗号
,到结尾的所有内容
效果验证
修改后执行Playbook,connecting_interface会直接返回干净的FiveGigabitEthernet1/0/48,可直接用于后续接口相关任务。
内容的提问来源于stack exchange,提问作者user2011902
相关产品推荐
相关产品推荐

