如何在Jinja2模板中引用变量变量 [英] how to reference variable variable in jinja2 template

查看:984
本文介绍了如何在Jinja2模板中引用变量变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的一个角色中,我想建立一个基本的网络/接口节,例如:

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模板中引用变量变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆