【问题标题】:Ansible when conditional with variable and itemAnsible 当有条件的变量和项目
【发布时间】:2021-07-11 16:30:38
【问题描述】:

我很难弄清楚我在使用 Ansible 剧本时做错了什么。

我有一堆任务,根据上下文定义或不定义一些变量,根据结果,某些任务将被忽略。

对于这种特定情况,我检查一个 VlanID 是否已经存在,如果不存在则我创建一个,并从结果中检索新的 VlanID。

这是剧本:

---
#Tasks for portGroup_add
- name: Get all portgroups in dvswitch vDS
  community.vmware.vmware_dvs_portgroup_find:
    hostname: "{{ vcenter_server }}"
    username: "{{ vcenter_user }}"
    password: "{{ vcenter_pass }}"
    dvswitch: "{{ vcenter_dvSwitch }}"
    validate_certs: False
  register: portGroup_infos
  when: (OLD_VLANID is not defined) or (OLD_VLANID|length < 1)

  #Get last VLAN ID for HDS client, and set VLANID + 1
- name: get portGroup_infos
  set_fact:
    VLANID: "{{ item.vlan_id }}"
  with_items: "{{ portGroup_infos.dvs_portgroups}}"
  when:
    - (portGroup_infos is defined) and (portGroup_infos|length > 0)
    - item.name | regex_search("\(HDS :\s*")

虽然对于大多数任务来说一切都很好,但这个会引发以下错误:

The conditional check 'item.name | regex_search("\(HDS :\s*")' failed. 
The error was: error while evaluating conditional (item.name | regex_search("\(HDS :\s*")): 'item' is undefined

这很明显,因为没有定义 dict portGroup_infos。

为了获取新的 VlanID,我使用了“when”条件,它检查项目中是否存在值“(HDS :”。

但是如果上面定义的 portGroup_infos 变量没有设置,我不希望任务启动,我虽然应该使用嵌套的“when”,但不能成功。

Ansible 版本:2.10.7 python版本:3.7.3

感谢您的帮助。

【问题讨论】:

  • - item.name is defined and item.name | regex_search("\(HDS :\s*")?
  • 不幸的是,同样的事情正在发生,弗拉基米尔的回答解决了这个问题。感谢您的帮助

标签: ansible yaml ansible-2.x


【解决方案1】:

将两个任务放在一个块中,例如

- block:
    - name: Get all portgroups in dvswitch vDS

      ...

    - name: get portGroup_infos

      ...

  when: OLD_VLANID|default('')|length == 0

【讨论】:

  • 非常感谢,现在一切正常。
猜你喜欢
  • 1970-01-01
  • 2021-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多