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

时间:2019-03-08 16:03:31

标签: ansible ansible-facts

我试图根据虚拟机的主机名查找它的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

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

1 个答案:

答案 0 :(得分:0)

由于lookup和它的vars朋友实际上是hostvars s,因此无需使用dict

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