【问题标题】:Ansible Strange conditional behaviorAnsible 奇怪的条件行为
【发布时间】:2021-07-13 20:23:56
【问题描述】:

我在尝试在字典中搜索时遇到了一个奇怪的问题。在上面的代码中,我试图用字典“VM_NETWORK_INFOS_PP”的“name”键的值定义一个新的 var“OLD_VLANID_PP”。

如果字典已设置且不为空,我希望定义 var,否则跳过任务。 为了测试条件是真还是假,我添加了一个调试任务,它应该显示字典的内容。

运行我的剧本时,调试任务确实表明条件不匹配,因此不显示我的字典,但 Ansible 继续尝试定义我的新 var,如输出所示,因此引发错误“ 'item' 未定义"

---
- block:
      #Search VCENTER for PPROD VM (If Windows to create => Search PG / EIther search Postgre)
    - name: Search for PPROD VM already created for the CLIENT {{ CLIENTNAME }} to retrieve VLANID
      set_fact:
        OLD_VMNAME_PP: "{{ item.guest_name }}"
      with_items: "{{ VM_EXIST_PP.virtual_machines }}"
      when: item.guest_name == VMNAME_PP
      delegate_to: localhost

  when: ENV != "PROD" and DEPLOY != "ALL" and (VM_EXIST_PP is defined) and (VM_EXIST_PP|length > 0)

#If we successfully found the previous VM for the client, then get its network info
- name: Retrieve PPROD VM {{ VMNAME_PP }} VLAN ID
  community.vmware.vmware_guest_network:
    hostname: "{{ vcenter_server }}"
    username: "{{ vcenter_user }}"
    password: "{{ vcenter_pass }}"
    datacenter: "{{ datacenter_name }}"
    validate_certs: False
    name: "{{ OLD_VMNAME_PP }}"
    gather_network_info: true
  register: VM_NETWORK_INFOS_PP
  when: (OLD_VMNAME_PP is defined) and OLD_VMNAME_PP != ""

- block:
  
    - debug: msg={{VM_NETWORK_INFOS_PP}}

    #If we successfully found the network info, set the OLD_VLANID with previous VM VLANID
    - set_fact:
        OLD_VLANID_PP: "{{ (item.name) | replace('(HDS : Client)','') | replace('VLAN0','') | replace('VLAN','') | replace(' ','') }}"
      with_items:
        - "{{ VM_NETWORK_INFOS_PP.network_info }}"
      when: item.name | regex_search('VLAN') and not item.name | regex_search('PVLAN')


  when: (VM_NETWORK_INFOS_PP is defined) and VM_NETWORK_INFOS_PP != ""

调试输出(应该显示字典内容):

ok: [127.0.0.1] => {
    "msg": {
        "changed": false,
        "skip_reason": "Conditional result was False",
        "skipped": true
    }
}

错误输出:

The error was: error while evaluating conditional (item.name | regex_search('VLAN') and not item.name | regex_search('PVLAN')): 'item' is undefined

Ansible 版本:2.10.7 Python版本:3.7.3

任何帮助将不胜感激。

谢谢

【问题讨论】:

  • 第一个debug 任务(debug: msg={{VM_NETWORK_INFOS_PP}})的输出是什么?
  • 查看我的帖子,我已经贴好了
  • 由于您的block 上的when 语句,现在它没有运行。将debug 语句移出块,以便我们可以看到VM_NETWORK_INFOS_PP 变量的内容。看起来好像变量实际上没有定义。
  • 感谢您的帮助,我刚刚编辑了帖子以显示整个代码和任务。最后一个 when 语句正是在这里检查是否定义了 VM_NETWORK_INFOS_PP 并避免此类错误。

标签: ansible yaml


【解决方案1】:

不确定这是否是正确的做法,但最终使用以下方法解决了这个问题:

when: item is defined and item.name | regex_search('VLAN') and not item.name | regex_search('PVLAN')

注意项目是在正则表达式搜索之前定义的

【讨论】:

    猜你喜欢
    • 2017-12-27
    • 2015-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-14
    • 2010-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多