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

如何在Ansible中遍历多列表并为每个VLAN配置不同描述

实现为每个VLAN配置对应自定义描述的Ansible方案

问题背景

现有Ansible Playbook可通过变量遍历创建VLAN,但当前所有VLAN使用统一的设备级描述,需要调整为给每个VLAN设置独立的自定义描述。

变量文件示例

现有变量格式

all_vlans:
- name: DEvice1
  vlan_id:
    - 5
    - 21
    - 32 
  description: SW1
  for_serial: "OVA192FA3"
  for_host: "aoscx_1"

期望变量格式

all_vlans:
- name: DEvice2
  vlan_id:
    - 11
    - 22
    - 32 
  vlan_desc:
    - VLAN_NO_11
    - VLAN_NO_22
    - VLANNO_32 
  description: SW2
  for_serial: "OVAA19FDF"
  for_host: "aoscx_2"

当前Playbook代码

- name: Create VLAN as Per Variables
    aoscx_vlan:
      vlan_id: "{{ item.1 }}"
      name: UPLINK_VLAN
      description: '{{ item.0.description }}'
      # admin_state: up
      state: create   #create,update,delete
    when: my_var == '{{ item.0.for_serial }}'

    loop: "{{ all_vlans|subelements('vlan_id') }}"
    loop_control:
      label: "{{ item.0.name }}"

解决方案

1. 变量文件调整(可选)

确保每个设备的vlan_id和vlan_desc列表长度完全一致,实现VLAN ID与描述的一一对应。对于不需要自定义描述的设备,可保留原description字段作为 fallback。

2. 修改Playbook代码

通过VLAN ID在列表中的索引匹配对应的自定义描述,同时保留原描述作为默认值:

- name: Create VLAN with custom descriptions
    aoscx_vlan:
      vlan_id: "{{ item.1 }}"
      name: UPLINK_VLAN
      # 优先使用vlan_desc中对应索引的描述,无则使用设备级description
      description: "{{ item.0.vlan_desc[item.0.vlan_id.index(item.1)] | default(item.0.description) }}"
      state: create
    when: my_var == item.0.for_serial
    loop: "{{ all_vlans | subelements('vlan_id', skip_missing=True) }}"
    loop_control:
      label: "{{ item.0.name }} - VLAN {{ item.1 }}"

关键说明

  • 使用item.0.vlan_id.index(item.1)获取当前VLAN ID在设备vlan_id列表中的位置索引
  • 通过索引从vlan_desc列表中取出对应的自定义描述
  • default(item.0.description)保证当设备没有vlan_desc字段时,仍使用原设备级描述
  • skip_missing=True避免因设备无vlan_id字段导致的报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 10:32:03