Ansible:每次迭代都建立一个对象数组

时间:2019-09-23 09:12:11

标签: arrays ansible

我有这个任务:

- name: Build array of Templates
  set_fact:
   template: 
     - name: "{{item.name}}"
       element1: "{{item.element1}}"
       element2: "{{item.element2}}"
 with_items: "{{list_of_objects}}"

我不知道每次迭代时如何将一次迭代中构建的模板对象添加到一组模板中。

在任务迭代结束时,我想做这样的事情(类似于python):

output = output + [template]

1 个答案:

答案 0 :(得分:1)

下面的戏

- hosts: localhost
  vars:
    list_of_objects:
      - name: A
        element1: A1
        element2: A2
      - name: B
        element1: B1
        element2: B2
  tasks:
    - set_fact:
        template: "{{ template|default([]) +
                      [{'name': item.name,
                        'element1': item.element1,
                        'element2': item.element2}] }}"
      loop: "{{ list_of_objects }}"
    - debug:
        var: template

给予

  template:
  - element1: A1
    element2: A2
    name: A
  - element1: B1
    element2: B2
    name: B

以下任务

- copy:
    content: |
      {{ template|to_yaml }}
    dest: /tmp/my_template.yaml
- copy:
    content: |
      {{ template|to_nice_json }}
    dest: /tmp/my_template.json

给予

$ cat /tmp/my_template.yaml 
- {element1: A1, element2: A2, name: A}
- {element1: B1, element2: B2, name: B}

$ cat /tmp/my_template.json 
[
    {
        "element1": "A1",
        "element2": "A2",
        "name": "A"
    },
    {
        "element1": "B1",
        "element2": "B2",
        "name": "B"
    }
]