当我试图在字典里搜索时,我正面临着一个奇怪的问题。在上面的代码中,我试图用字典"OLD_VLANID_PP“的"name”键的值定义一个新的var "VM_NETWORK_INFOS_PP“。
如果字典是设置的,而不是空的,我希望定义var,否则就跳过任务。为了测试条件是真还是假,我添加了一个调试任务,它应该显示字典的内容。
运行我的剧本时,调试任务确实指示条件不匹配,因此不显示我的字典,但是Ansible继续尝试定义输出中所示的新变量,因此引发了一个错误"'item‘is Un定义“
---
- 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 undefinedAnsible版本: 2.10.7 Python版本: 3.7.3
任何帮助都将不胜感激。
谢谢
发布于 2021-04-20 09:54:09
不确定这是否是正确的做法,但最终使用以下方法解决了这一问题:
when: item is defined and item.name | regex_search('VLAN') and not item.name | regex_search('PVLAN')注意,项在regex搜索之前定义为。
https://stackoverflow.com/questions/67165378
复制相似问题