带变量和项的条件时为Ansible

带变量和项的条件时为Ansible,ansible,yaml,ansible-2.x,Ansible,Yaml,Ansible 2.x,我很难弄清楚我的Ansible剧本到底做错了什么 我有一堆任务,它们根据上下文定义或不定义一些变量,根据结果,一些任务将被忽略或不被忽略 对于这种特定情况,我检查VlanID是否已经存在,如果不存在,则创建一个,并从结果中检索新的VlanID 这是剧本: --- #Tasks for portGroup_add - name: Get all portgroups in dvswitch vDS community.vmware.vmware_dvs_portgroup_find:

我很难弄清楚我的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*")
这很明显,因为dict portGroup_infos没有定义

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

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

Ansible版本:2.10.7 python版本:3.7.3


谢谢您的帮助。

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

-块:
-名称:获取dvswitch vDS中的所有端口组
...
-名称:获取端口组信息
...
当:OLD_VLANID | default(“”)| length==0

-item.name已定义,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