2016-11-23 97 views
1

我需要爲調配多個以太網連接創建劇本。模板中的Ansible嵌套變量

如何從事實和用戶變量中獲取模板中嵌套變量的混合?

正是我需要的,例如:

{{ ansible_{{ net1 }}.macaddress }} 
{{ ansible_{{ net2 }}.macaddress }} 

變量net1net2等在hosts_vars定義方式:

net1: eth0 
net2: br0 

是否有可能呢?如果答案是肯定的,那麼如何?

回答

1

有幾種方法可以做到這一點。

您可以使用任務變量或使用字典語法來訪問變量。

這裏有一個劇本證明這兩種方法:對於test.org

- hosts: test.org 
    tasks: 
    - debug: 
     var: "{{ tmp_mac }}" 
     vars: 
     tmp_mac: ansible_{{net1}}.macaddress 
    - debug: 
     var: "hostvars[inventory_hostname]['ansible_' + net1]['macaddress']" 

主機變量文件:

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可變嵌套「可能是一個好主意。

+0

謝謝德米特里,這非常有用。 – Ilya