仅当Nexus交换机上不存在VLAN时才创建VLAN

时间:2018-09-21 12:42:51

标签: ansible

我正试图创建一个Ansible剧本,仅当设备上不存在VLAN时,才应在Cisco Nexus交换机上的文件vlans.dat中创建VLAN。

文件vlans.dat包含:

---
vlans:
  - { vlan_id: 2, name: TEST }

和Ansible文件:

---
- name: Verify and create VLANs
  hosts: switches_group
  gather_facts: no
  vars_files:
    - vlans.dat
  tasks:
     - name: Get Nexus facts
       nxos_facts:
       register: data
     - name: Create new VLANs only
       nxos_vlan:
        vlan_id: "{{ item.vlan_id }}"
        name: "{{ item.name }}"
        state:   "{{item.state | default('present') }}"
       with_items: "{{ vlans }}"
       when:  item.vlan_id not in data.ansible_facts.vlan_list

在when语句中,我试图将执行仅限于vlan_id模块收集的vlan_list中不存在nxos_facts(在文件中定义)的情况。不幸的是,即使vlan_id中已经存在vlan_list,它也被执行了,我不知道为什么?

PLAY [Verify and create VLANs]     
TASK [Get Nexus facts] 
 ok: [10.1.1.1]
TASK [Create new VLANs only] 
 ok: [10.1.1.1] => (item={u'name': u'TEST', u'vlan_id': 2})
TASK [debug] 
 skipping: [10.1.1.1]

PLAY RECAP 
 10.1.1.1   : ok=2    changed=0    unreachable=0 failed=0

您能帮我解决这个问题还是提供一些解决方案?

1 个答案:

答案 0 :(得分:0)

似乎您偶然发现了具有实际类型的YAML的副作用。因为在{vlan_id: 2}中2是int,但是列表是字符串。您可能会想到{{ 1 in ["1"] }}False

有两种方法可以解决此问题:通过vlan_id- { vlan_id: "2" }设置为字符串,或将vlan_id强制转换为仅用于测试列表成员资格的字符串:

when:  (item.vlan_id|string) not in data.ansible_facts.vlan_list