Ansible add multiple list variables to form a master list

Viewed 790

I have multiple lists in my playbook, app1, app2, app3, ..., appN. How can I merge them to a single list, called app.
I have the N value. What I need is this

app = app1 + app2 + ... + appN

I'm using Ansible version 2.9.18.

2 Answers

I don't know how you are getting the values for the different appN values, but if you want to flat multiples lists into a single one, you can use the + operator.

Here is an example on how you might use it:

- hosts: localhost
  gather_facts: no
  vars:
    app1: [1, 1, 1]
    app2: [2, 2, 2]
    app3: [3, 3, 3]
  tasks:
    - set_fact:
        app: |
          {{
            (app | default([]))
            +
            item
          }}
      loop:
        - "{{ app1 }}"
        - "{{ app2 }}"
        - "{{ app3 }}"

    - debug:
        var: app

I use the default filter to handle the fact that the app variable is not defined initially. You can apply this operator in multiple ways, so you can adapt it to whatever you are using.

And to close the gap between @guzmonne's answer and your requirement, you can use a couple of a loop with range and the vars lookup.

Which gives, given that N is defined as an integer:

- set_fact:
    app: "{{ app | default([]) + lookup('vars', 'app' ~ item) }}"
  loop: "{{ range(1, N+1) | list }}"

Given the playbook:

- hosts: localhost
  gather_facts: no
  vars:
    N: 4
    app1: 
      - a
      - b
    app2: 
      - c
      - d
    app3: 
      - e
      - f
    app4: 
      - g
      - h


  tasks:
    - set_fact:
        app: "{{ app | default([]) + lookup('vars', 'app' ~ item) }}"
      loop: "{{ range(1, N+1) | list }}"

    - debug:
        var: app

This yields the recap:

PLAY [localhost] **************************************************************************************************

TASK [set_fact] ***************************************************************************************************
ok: [localhost] => (item=1)
ok: [localhost] => (item=2)
ok: [localhost] => (item=3)
ok: [localhost] => (item=4)

TASK [debug] ******************************************************************************************************
ok: [localhost] => 
  app:
  - a
  - b
  - c
  - d
  - e
  - f
  - g
  - h

PLAY RECAP ********************************************************************************************************
localhost                  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
Related