how to reference variable variable in jinja2 templ

2019-09-18 23: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.