使用另一个变量检索变量的语法

Syntax for retrieving variable using another variable

我正在尝试根据主机名查找 VM 的 UUID。我不确定这里的语法中缺少什么,但我尝试了几种不同的方法。这是我目前正在使用的示例剧本:

---

- name: Test taking snapshot by UUID
  hosts: tst000.company.com
  vars_files:
    - vars/credentials.yml

  tasks:
    - name: Gather all registered virtual machines
      vmware_vm_facts:
        hostname: 'vcenter.company.com'
        username: '{{ vcenter.username }}'
        password: '{{ vcenter.password }}'
        validate_certs: False
      delegate_to: localhost
      register: vmfacts

    - debug:
        var: vmfacts.virtual_machines.{{ ansible_facts['hostname'] }}.uuid

    - set_fact:
        vm_uuid: "{{ lookup('vars', 'vmfacts.virtual_machines.' + ansible_facts['hostname'] + '.uuid') }}"

结果如下:

 Identity added: /opt/tmp/awx_2507_ithHYD/credential_3
 (/opt/tmp/awx_2507_ithHYD/credential_3) Vault password: 

 PLAY [Test taking snapshot by UUID]
 ********************************************


 TASK [Gathering Facts]
 ********************************************************* ok: [tst000.company.com]

 TASK [Gather all registered virtual machines]
 ********************************** ok: [tst000.company.com -> localhost]

 TASK [debug]
 ******************************************************************* ok: [tst000.company.com] => {
     "vmfacts.virtual_machines.tst000.uuid": "421d2491-8896-e52f-e4f5-5118687ce0e9" }

 TASK [set_fact]
 **************************************************************** fatal: [tst000.company.com]: FAILED! => {"msg": "The task
 includes an option with an undefined variable. The error was: No
 variable found with this name:
 vmfacts.virtual_machines.tst000.uuid\n\nThe error appears to
 have been in '/var/lib/awx/projects/quick-stuff/test_snapshot.yml':
 line 21, column 7, but may\nbe elsewhere in the file depending on the
 exact syntax problem.\n\nThe offending line appears to be:\n\n\n 
 - set_fact:\n      ^ here\n"}

 PLAY RECAP
 ********************************************************************* tst000.company.com : ok=3    changed=0    unreachable=0   
 failed=1

在调试和 set_fact 模块中,您可以看到 ansible_facts['hostname]' 根据需要正确放置了主机名,但是,它 returns 是正确的值在调试模块中,但声称在 set_fact 模块中找不到该名称的变量。我不确定这里的语法有什么问题。

没有必要以这种方式使用 lookup,因为 vars 及其 hostvars 朋友实际上是 dicts:

- set_fact:
    vm_uuid: "{{ vmfacts.virtual_machines[ansible_facts['hostname']].uuid }}"