1

I have this Ansible task:

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

I don’t know how to add the template object I build in one iteration to an array of templates every time I iterate.

At the end of the task iteration, I want to do something like this (python like):

output = output + [template]

1 Answer 1

2

The play below

- 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

gives

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

The tasks below

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

give

$ 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"
    }
]
Sign up to request clarification or add additional context in comments.

2 Comments

Yes! Thanks a lot!
If I try to save template in a file with copy module I get this error: 'list' object has no attribute 'endswith'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.