Ansible: Dynamic lists

Hi there,

In the last few days I needed to use lists in ansible which are extended and manipulated at runtime. So I will leave a short code snipped here - maybe it is useful for you too:

- hosts: localhost
  connection: local
  vars:
    my_list: [ "Hello", "World", "this", "is", "just", "a", "list", "of", "strings" ]
  tasks:
    - name: build list with all items with an 'i' in it
      set_fact:
        my_dynamic_list: "{{ my_dynamic_list|default([]) + [ item ] }}"
      loop: "{{ my_list }}"
      when: "'i' in item"
      
    - name: print results
      debug:
        msg: "{{ my_dynamic_list }}"
PLAY [localhost] ****************************************************************************

TASK [Gathering Facts] ****************************************************************************
ok: [localhost]

TASK [build list with all items an 'i' in it] ********************************************************************************************************************************************************
skipping: [localhost] => (item=Hello) 
skipping: [localhost] => (item=World) 
ok: [localhost] => (item=this)
ok: [localhost] => (item=is)
skipping: [localhost] => (item=just) 
skipping: [localhost] => (item=a) 
ok: [localhost] => (item=list)
skipping: [localhost] => (item=of) 
ok: [localhost] => (item=strings)

TASK [print results] ********************************************************************************************************************************************************
ok: [localhost] => {
    "msg": [
        "this",
        "is",
        "list",
        "strings"
    ]
}

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

Short explanation

First, a list of sample values "my_list" is defined. The first task then iterates through all elements of "my_list". In addition, the task is given the condition

if: "'i' in item"

In other words, the task will only be executed if the item contains the letter "i". If the condition is true, the item will be added to the target list. The Jinja2 filter 'default':

my_dynamic_list: "{{ my_dynamic_list|default([]) + [ item ] }}"

basically intercepts the first run for which the list "my_dynamic_list" does not yet exist, and returns an empty list in this case. Since you can only append another list - and not a string - to a list, we define the string in a list with a single item:

... [ item ] ...

Maybe some of you will find this little code snippet useful :)

Regards!