2017-12-18 471 views
2

有沒有辦法將Ansible Playbook中的對象數組映射到不同的對象數組?比方說,我們有一個源陣列之中:Ansible - 將對象數組映射到不同的對象數組

arr: 
    - value: a 
    - value: b 
    - value: c 

而我們想要的是讓基於第一陣列中的對象不同的數組,讓我們說:

arr2: 
    - const: 1 
    var: a 
    - const: 1 
    var: b 
    - const: 1 
    var: c 

這將是可行的利用元素模板:

const: 1 
var: {{ value }} 

有沒有辦法將這樣的模板應用到數組中的每個元素?我還沒有找到合適的map過濾器,因爲lookup('template', ...)不能在map內部使用。

+0

請檢查https://stackoverflow.com/questions/42152192/ansible-how-to-apply-defaults-to-each-complex-arguments-of-a-list/42152622#42152622 –

回答

0

正如Konstantin Suvorov在評論中提到的那樣,它可以使用遞歸數組構建完成。這是我做的:

#role test 
--- 
- hosts: localhost 
    gather_facts: no 
    vars: 
    arr: 
     - value: a 
     - value: b 
     - value: c 

    tasks: 
    - set_fact: 
     arr2: "{{ (arr2 | default([])) + [ lookup('template', 'template.yaml.j2') | from_yaml ] }}" 
     with_items: "{{ arr }}" 
    - debug: 
     msg: "{{ arr2 }}" 


#template.yaml.j2 
const: 1 
var: {{ item.value }}