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

Ansible查询交换机端口描述并追加内容时变量引用失败问题

问题分析与解决

你遇到的问题是因为直接引用了ios_command模块返回的完整字典对象,而没有提取其中的端口描述文本内容。

原因详解

ios_command模块执行后返回的interface_description是一个包含多个键的字典,从你的输出可以看到它的结构:

{
    "failed": False,
    "changed": False,
    "stdout_lines": [["description DataJack123"]],
    "stdout": ["description DataJack123"]
}

其中实际的命令输出内容存在于stdout列表(对应每条命令的输出),因为你只执行了一条命令,所以取stdout[0]就能拿到完整的描述行,之后还需要去掉前缀description 才能得到纯描述文本。

修正后的Playbook代码

- name: Verifying Interface Description
  ios_command:
    provider:
      username: "{{ username }}"
      password: "{{ password }}"
    commands:
      - command: "show derived-config interface GigabitEthernet{{ switch_interface }} | include description"
  register: interface_description

- name: Extract pure description text
  set_fact:
    # 用split分割前缀,取后半段纯描述
    pure_description: "{{ interface_description.stdout[0].split('description ')[1] }}"
    # 也可以用正则替换,适配格式更灵活的场景
    # pure_description: "{{ interface_description.stdout[0] | regex_replace('^description ', '') }}"

- debug:
    msg: "{{ pure_description }} Updated {{ ansible_date_time.date }}"

修正后输出效果

执行后debug模块会输出预期的纯描述+日期:

TASK [debug] *************************************************************************************************************************************************************************************************
ok: [NG-1-DA] => {
    "msg": "DataJack123 Updated 2024-04-23"
}

后续功能扩展(可选)

如果要实现重新应用描述并追加文本及日期的目标,可以添加ios_config模块来配置交换机:

- name: Update interface description with appended content
  ios_config:
    provider:
      username: "{{ username }}"
      password: "{{ password }}"
    lines:
      - description {{ pure_description }} - Updated on {{ ansible_date_time.date }}
    parents: interface GigabitEthernet{{ switch_interface }}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 14:03:28