我需要创建用于配置多个以太网连接的playbook。
如何从事实和用户变量中混合模板中的嵌套变量?
我确实需要它,例如:
{{ ansible_{{ net1 }}.macaddress }}
{{ ansible_{{ net2 }}.macaddress }}
以net1
方式定义的变量net2
,hosts_vars
等:
net1: eth0
net2: br0
有可能吗?如果答案是肯定的,那么如何?
答案 0 :(得分:1)
有几种方法可以做到这一点。
您可以使用任务变量或使用字典语法来访问变量。
这是一本演示两种方法的剧本:
- hosts: test.org
tasks:
- debug:
var: "{{ tmp_mac }}"
vars:
tmp_mac: ansible_{{net1}}.macaddress
- debug:
var: "hostvars[inventory_hostname]['ansible_' + net1]['macaddress']"
test.org
的主机变量文件:
net1: enp3s0
输出:
ok: [test.org] => {
"ansible_enp3s0.macaddress": "e8:b0:00:b5:bf:e2"
}
ok: [test.org] => {
"hostvars[inventory_hostname]['ansible_' + net1]['macaddress']": "e8:b0:00:b5:bf:e2"
}
Ansible使用Jinja2模板,因此搜索“Jinja2变量嵌套”可能是一个好主意。