我如何使用Ansible嵌套变量?

qia*_*ang 11 jinja2 ansible

我有一个像下面这样的Ansible剧本,我想使用这样的嵌套变量: msg={{{{Component}}.community_release_num}},但是当我运行playbook时:

ansible-playbook vartest.yml -e 'version=version_402', it not work 

[es@vpn-server nested-var]$ tree
.
??? vars
?   ??? horizon.yml
?   ??? version_402.yml
??? vartest.yml

1 directory, 3 files
[es@vpn-server nested-var]$ cat vartest.yml 
---

- name: test 
  hosts: localhost
  vars_files:
    - vars/{{version}}.yml
  tasks:
    - debug: msg={{{{Component}}.community_release_num}}
    - debug: msg={{{{Component}}.release_num}}

[es@vpn-server nested-var]$ cat vars/horizon.yml 
Component: horizon

[es@vpn-server nested-var]$ cat vars/version_402.yml 
- horizon:
   community_release_num: '9.0.1'
   release_num: '4.0.2'
[es@vpn-server nested-var]$
Run Code Online (Sandbox Code Playgroud)

错误消息

[es@vpn-server nested-var]$ ansible-playbook vartest.yml -e 'version=version_402'
/usr/lib64/python2.6/site-packages/cryptography/__init__.py:25: DeprecationWarning: Python 2.6 is no longer supported by the Python core team, please upgrade your Python.
  DeprecationWarning

PLAY [test] *******************************************************************************************************
/usr/lib64/python2.6/site-packages/Crypto/Util/number.py:57: PowmInsecureWarning: Not using mpz_powm_sec.  You should rebuild using libgmp >= 5 to avoid timing attack vulnerability.
  _warn("Not using mpz_powm_sec.  You should rebuild using libgmp >= 5 to avoid timing attack vulnerability.", PowmInsecureWarning)

TASK [debug] ******************************************************************************************************
fatal: [localhost]: FAILED! => {"failed": true, "msg": "template error while templating string: expected token 'colon', got '}'. String: {{{{Component}}.community_release_num}}"}
    to retry, use: --limit @/data/wangqian/artemis-code-test/artemis/ansible/update/nested-var/vartest.retry

PLAY RECAP ********************************************************************************************************
localhost                  : ok=0    changed=0    unreachable=0    failed=1  
Run Code Online (Sandbox Code Playgroud)

Can Ansible可以使用嵌套变量,如果是,如何使用它?

tec*_*raf 20

Per Ansible FAQ:

另一条规则是'胡须不叠加'.我们经常看到这个:

{{ somevar_{{other_var}} }} 
Run Code Online (Sandbox Code Playgroud)

如果您需要使用动态变量,则上述操作无效,请根据需要使用hostvars或vars字典:

{{ hostvars[inventory_hostname]['somevar_' + other_var] }}
Run Code Online (Sandbox Code Playgroud)

所以在你的情况下:

- debug: msg={{hostvars[inventory_hostname][Component].community_release_num}}
Run Code Online (Sandbox Code Playgroud)

要么:

- debug: msg={{vars[Component].community_release_num}}
Run Code Online (Sandbox Code Playgroud)

或者(因为Ansible 2.5):

- debug: msg={{(lookup('vars', Component)).community_release_num}}
Run Code Online (Sandbox Code Playgroud)