【问题标题】:how to reference variable variable in jinja2 template如何在jinja2模板中引用变量变量
【发布时间】:2015-12-08 03:27:13
【问题描述】:

在我的一个 ansible 角色中,我想设置一个基本的网络/接口节,如下所示:

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

我有变量,我使用 jinja2 模板创建节:

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

我可以在模板中引用变量变量吗?我还尝试在 ansible yaml 中创建一个变量,例如 nserver: ansible_{{iface}}.ipv4.address,但也没有用!

【问题讨论】:

    标签: django-templates jinja2 ansible


    【解决方案1】:

    您可以使用内置的hostvars dict 变量来引用主机的变量。

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

    inventory_hostname 是 Ansible 已知的当前主机的名称。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多