问题描述
在我的一个角色中,我想建立一个基本的网络/接口节,例如:
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
我有变量,并使用jinja2模板创建了节:
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
我可以在模板中引用变量变量吗?我还尝试在ansible yaml中创建一个变量,例如nserver:ansible _ {{{iface}}。ipv4.address,该方法也不起作用!
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!
推荐答案
您可以使用内置的 hostvars
dict变量引用主机的变量。
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
是Ansible知道的当前主机的名称。
inventory_hostname
is name of current host as known by Ansible.
这篇关于如何在Jinja2模板中引用变量变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!