how to reference variable variable in jinja2 template

。_饼干妹妹 提交于 2019-12-12 00:22:01

问题


In one of my ansible roles I would like to set up a basic network/interfaces stanza, like this:

auto eth1
ifaces eth1 inet dhcp
    dns-nameserver {{ ansible_eth1.ipv4.address }}
    dns-search maas

I have variables, and I create the stanza with the jinja2 template:

auto {{ iface }}
ifaces {{ iface}} inet dhcp
    dns-nameserver {{ ansible_{{ iface }}.ipv4.address }}
    dns-search maas

Can I reference a variable variable in a template? I also tried creating a variable in the ansible yaml, like nserver: ansible_{{iface}}.ipv4.address, that didn't work either!


回答1:


You can use built-in hostvars dict variable to reference variables of host.

auto {{ iface }}                                                                 
iface {{ iface }} inet dhcp    
    dns-nameserver {{ hostvars[inventory_hostname]['ansible_'+ iface]['ipv4']['address'] }}
    dns-search maas

inventory_hostname is name of current host as known by Ansible.



来源:https://stackoverflow.com/questions/32525652/how-to-reference-variable-variable-in-jinja2-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!