![Ansible - 无法打印自定义事实的值](https://linux22.com/image/770826/Ansible%20-%20%E6%97%A0%E6%B3%95%E6%89%93%E5%8D%B0%E8%87%AA%E5%AE%9A%E4%B9%89%E4%BA%8B%E5%AE%9E%E7%9A%84%E5%80%BC.png)
这是与 vmware 对话的角色的剧本部分。
我正在尝试设置自定义事实(目标虚拟机)接收虚拟机名称。
但是当我使用调试模块打印它的值时,它似乎为空。
似乎设置事实正确设置,因为调试输出显示{“ansible_facts”:{“target_vm”:“TESTVM”}。
我还创建了一个失败任务,用于显示 target_vm 事实是否已设置。
这是 Playbook
- delegate_to: localhost
become: no
delegate_facts: yes
vars:
vc_hostname: 'vcenter.bio.local'
vc_username: 'bio.local\ansible'
vc_password: "{{ v_pass }}"
vm_uuid: '4217200F-46D2-C9FD-E7FD-768D21B327E8' | lower
block:
- name: Gather only registered virtual machines
vmware_vm_info:
hostname: '{{ vc_hostname }}'
username: '{{ vc_username }}'
password: '{{ vc_password }}'
validate_certs: False
vm_type: vm
delegate_to: localhost
register: virtual_info
no_log: true
- name: Get VM name from UUID
set_fact:
target_vm: "{{ my_item.guest_name }}"
loop: "{{ virtual_info.virtual_machines }}"
when: my_item.uuid == vm_uuid
loop_control:
loop_var: my_item
delegate_to: localhost
delegate_facts: True
- name: Verify interface name is set
fail:
msg: "Could not determine target_vm name!"
when: target_vm is not defined
- name: Print Output
debug:
msg: "The VM name is: {{ target_vm }}"
这是输出
TASK [vmwaretaks : Get VM name from UUID] ***************************************************************************************
ok: [testvm] => (item={'guest_name': 'TESTVM', 'guest_fullname': 'Red Hat Enterprise Linux 6 (64-bit)', 'power_state': 'poweredOn', 'ip_address': '192.168.54.32', 'mac_address': ['00:32:52:97:e9:c8'], 'uuid': '4217200f-46d2-c9fd-e7fd-768d21b327e8', 'vm_network': {'00:32:52:97:e9:c8': {'ipv4': ['192.168.54.32'], 'ipv6': ['fe80::250:56ff:fe97:d4c3']}}, 'esxi_hostname': 'b3j15esx05.bio.local', 'cluster': 'JAS-Lab-DEP', 'attributes': {}, 'tags': []}) => {"ansible_facts": {"target_vm": "TESTVM"}, "ansible_loop_var": "my_item", "changed": false, "my_item": {"attributes": {}, "cluster": "JAS-Lab-DEP", "esxi_hostname": "b3j15esx05.bio.local", "guest_fullname": "Red Hat Enterprise Linux 6 (64-bit)", "guest_name": "TESTVM", "ip_address": "192.168.54.32", "mac_address": ["00:32:52:97:e9:c8"], "power_state": "poweredOn", "tags": [], "uuid": "4217200f-46d2-c9fd-e7fd-768d21b327e8", "vm_network": {"00:32:52:97:e9:c8": {"ipv4": ["192.168.54.32"], "ipv6": ["fe80::250:56ff:fe97:d4c3"]}}}}
TASK [vmwaretaks : Verify interface name is set] ********************************************************************************
fatal: [testvm]: FAILED! => {"changed": false, "msg": "Could not determine target_vm name!"}
PLAY RECAP **********************************************************************************************************************
testvm : ok=13 changed=0 unreachable=0 failed=1 skipped=2 rescued=0 ignored=0
答案1
您已delegate_facts: True
开始执行set_fact
任务,因此您正在为 localhost 设置变量。然后,您尝试在播放主机的上下文中访问它,但播放主机尚未设置它。
您必须决定将其设置在哪里。如果 localhost 正确,则需要通过 hostvars ( hostvars['localhost']['testvm']
) 访问它;如果不正确,则需要删除delegate_facts
。