You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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(',.*$', '') }}"

这个逻辑是:

  1. 移除从开头到Interface: 的所有内容
  2. 移除从逗号 ,到结尾的所有内容

效果验证

修改后执行Playbook,connecting_interface会直接返回干净的FiveGigabitEthernet1/0/48,可直接用于后续接口相关任务。

内容的提问来源于stack exchange,提问作者user2011902

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 16:05:05