If you really want to append to content, you will need to use the set_fact module. But if you just want to use the merged lists it is as easy as this:

{{ list1 + list2 }}

With set_fact it would look like this:

- set_fact:
    list_merged: "{{ list1 + list2 }}"

NOTE: If you need to do additional operations on the concatenated lists be sure to group them like so:

- set_fact:
    list_merged: "{{ (list1 + list2) | ... }}"
Answer from udondan on Stack Overflow
🌐
GitHub
github.com › betrcode › ansible-append-list
GitHub - betrcode/ansible-append-list: How to append to a list in Ansible · GitHub
In this repository you can find examples of how to append things to lists in Ansible.
Starred by 48 users
Forked by 22 users
Discussions

Appending an item to a list
You need to remove the double quotes within your brackets and keep your variables closed; (Still on mobile :D ) p: “{{ port_map }} + [{{ another }}:80]” More on reddit.com
🌐 r/ansible
5
2
February 28, 2023
python - Append a list with loop in Ansible - Stack Overflow
I'm trying to append new tunnel interface to empty list, but I'm getting the below error. - name: empty list set_fact: list_tunnel: [] - name: create new list for tunnel set_fact: ... More on stackoverflow.com
🌐 stackoverflow.com
Append a string to a List in Ansible - Stack Overflow
I'm trying to append a string to a list in ansible , so basically i'll be building a payload to delete few of the topology records in the F5 GTM network gear. I was able to create one single list w... More on stackoverflow.com
🌐 stackoverflow.com
ansible - cannot append into a list in a with_items loop - Stack Overflow
take this playbook for example: --- - hosts: localhost gather_facts: no vars: in_list: - value1 - value2 - value3 final_list: [] tasks: - debug: var: More on stackoverflow.com
🌐 stackoverflow.com
April 23, 2018
🌐
Medium
medium.com › @AbhijeetKasurde › ansible-adding-an-element-to-the-list-9e9464caf37c
Ansible: Adding an element to the list | by Abhijeet Kasurde | Medium
July 6, 2023 - To add an element to an existing list in Ansible, we can leverage the set_fact module. This module allows us to set or modify variables dynamically during playbook execution. The set_fact module, combined with Ansible's powerful Jinja2 templating ...
🌐
Middleware Inventory
middlewareinventory.com › blog › ansible-list-examples-how-to-create-and-append-items-to-list
Ansible List Examples - How to create and append items to List
February 16, 2022 - As I have mentioned to append a new item to the Ansible list. we have to put the values inside the empty list with [ ] and use + sign to merge them
Top answer
1 of 6
19

You can merge two lists in a variable with +. Say you have a group_vars file with this content:

---
# group_vars/all
pgsql_extensions:
  - ext1
  - ext2
  - ext3

And it's used in a template pgsql.conf.j2 like:

# {{ ansible_managed }}
pgsql_extensions={% for item in pgsql_extensions %}{{ item }}, {% endfor %}

You can then append extensions to the testing database servers like this:

---
# group_vars/testing_db
append_exts:
  - ext4
  - ext5
pgsql_extensions: "{{ pgsql_extensions + append_exts }}"

When the role is run in any of the testing servers, the aditional extensions will be added.

I'm not sure this works for dictionaries as well, and also be careful with spaces and leaving a dangling comma at the end of the line.

2 of 6
50

Since Ansible v2.x you can do these:

# use case I: appending to LIST variable:
- name: my appender
  set_fact:
    my_list_var: '{{my_list_myvar + new_items_list}}'

# use case II: appending to LIST variable one by one:
- name: my appender
  set_fact:
    my_list_var: '{{my_list_var + [item]}}'
  with_items: '{{my_new_items|list}}'

# use case III: appending more keys DICT variable in a "batch":
- name: my appender
  set_fact:
    my_dict_var: '{{my_dict_var|combine(my_new_keys_in_a_dict)}}'

# use case IV: appending keys DICT variable one by one from tuples
- name: setup list of tuples (for 2.4.x and up
  set_fact:
    lot: >
      [('key1', 'value1',), ('key2', 'value2',), ..., ('keyN', 'valueN',)],
- name: my appender
  set_fact:
    my_dict_var: '{{my_dict_var|combine({item[0]: item[1]})}}'
  with_items: '{{lot}}'

# use case V: appending keys DICT variable one by one from list of dicts (thanks to @ssc)
- name: add new key / value pairs to dict
  set_fact:
    my_dict_var: "{{ my_dict_var | combine({item.key: item.value}) }}"
  with_items:
  - { key: 'key01', value: 'value 01' }
  - { key: 'key02', value: 'value 03' }
  - { key: 'key03', value: 'value 04' }

all the above is documented in: https://docs.ansible.com/ansible/latest/user_guide/playbooks_filters.html#combining-hashes-dictionaries

🌐
Reddit
reddit.com › r/ansible › appending an item to a list
r/ansible on Reddit: Appending an item to a list
February 28, 2023 -

I just want to do something very simple: I want to store a new list that combines other values. I tried with

    port_mapping:
      - "10025:25"
      - "10143:143"

published_ports: "{{ port_mapping + ["{{ another_port }}:80"] }}"

as well as with

published_ports: "{{ mailserver_port_mapping.concat("{{ another_port }}:80") }}"

But obviously I'm misunderstanding examples like this.

Maybe it's not as intuitive as I thought.

🌐
FreeKB
freekb.net › Article
Ansible - Append elements to a List
February 3, 2024 - The lookup plugin and with_items parameter can be used to append each line in a file on the control node to a list.
Find elsewhere
🌐
TTL255
ttl255.com › ansible-appending-to-lists-and-dictionaries
Ansible - Appending to lists and dictionaries |
January 27, 2020 - Normally when trying to add a new item to the variable, while in the loop, or between tasks, Ansible will ovewrite the values, keeping the result of the last iteration. For example, let's see what will be the result of running the following playbook: --- - name: Append to list hosts: localhost vars: cisco: - CiscoRouter01 - CiscoRouter02 - CiscoRouter03 - CiscoSwitch01 arista: - AristaSwitch01 - AristaSwitch02 - AristaSwitch03 tasks: - name: Add Cisco and Airsta devices to the list set_fact: devices: "{{ item }}" with_items: - "{{ cisco }}" - "{{ arista }}" - name: Debug list debug: var: devices verbosity: 0
🌐
Jeff Geerling
jeffgeerling.com › blog › 2017 › adding-strings-array-ansible
Adding strings to an array in Ansible - Jeff Geerling
June 16, 2017 - - hosts: localhost connection: local gather_facts: no vars: ec2_security_group_names: [] tasks: - name: Get security groups from EC2. ec2_group_facts: region: us-east-1 filters: "tag:myapp": "example" register: ec2_security_groups - name: Build a list of all the security group names. set_fact: ec2_security_group_names: "{{ ec2_security_group_names }} + [ '{{ item.group_name }}' ]" with_items: "{{ ec2_security_groups.security_groups }}" - name: Print the security group names to the console.
🌐
Crisp's Blog
blog.crisp.se › 2016 › 10 › 20 › maxwenzin › how-to-append-to-lists-in-ansible
How to append to lists in Ansible - Crisp's Blog
February 8, 2019 - Since I have found the Ansible documentation to be lacking, and StackOverflow insufficient in this matter, I feel the need to share how you can append to a list using Ansible. I’ve created a…
Top answer
1 of 3
11

Q: "Prepend a string 'delete' in front of each item."

A: Is this what you're looking for?

- hosts: localhost
  vars:
    info: ['a', 'b', 'c']
  tasks:
    - set_fact:
        payload: "{{ payload|default([]) + ['delete ' ~ item] }}"
      loop: "{{ info }}"
    - debug:
        var: payload

gives (abridged)

payload:
  - delete a
  - delete b
  - delete c

The same result can be achieved without iteration (credit @Romain DEQUIDT)

- hosts: localhost
  vars:
    info: ['a', 'b', 'c']
    payload: "{{ ['delete']|product(info)|map('join', ' ')|list }}"
  tasks:
    - debug:
        var: payload

Q: "Prepend a string 'delete' in front of each output that starts with 'gtm topology'."

A: Use the test search

- hosts: localhost
  gather_facts: false
  vars:
    info: ['a', 'gtm topology', 'c']
  tasks:
    - set_fact:
        payload: "{{ payload|default([]) + ['delete ' ~ item] }}"
      loop: "{{ info }}"
      when: item is search('^gtm topology')
    - debug:
        var: payload

gives (abridged)

payload:
  - delete gtm topology

The same result can be achieved without iteration

- hosts: localhost
  vars:
    info: ['a', 'gtm topology', 'c']
    info_gtm_topology: "{{ info|select('search', '^gtm topology') }}"
    payload: "{{ ['delete']|product(info_gtm_topology)|map('join', ' ')|list }}"
  tasks:
    - debug:
        var: payload

Q: "In addition to the conditions above, process the list till 'test-pool1' is found."

A: Use the test search also to find the index of the last item

  hosts: localhost
  vars:
    info: ['a', 'gtm topology 1', 'c', 'test-pool1', 'gtm topology 2', 'd']
    stop_regex: '.*pool1.*'
    stop_items: "{{ info|select('search', stop_regex) }}"
    stop_index: "{{ info.index(stop_items.0) }}"
  tasks:
    - set_fact:
        payload: "{{ payload|default([]) + ['delete ' ~ item] }}"
      loop: "{{ info[:stop_index|int] }}"
      when: item is search('^gtm topology')
    - debug:
        var: payload

gives (abridged)

payload:
  - delete gtm topology 1

The same result can be achieved without iteration

- hosts: localhost
  vars:
    info: ['a', 'gtm topology 1', 'c', 'test-pool1', 'gtm topology 2', 'd']
    stop_regex: '.*pool1.*'
    stop_items: "{{ info|select('search', stop_regex) }}"
    stop_index: "{{ info.index(stop_items.0) }}"
    info_gtm_topology: "{{ info[:stop_index|int]|select('search', '^gtm topology') }}"
    payload: "{{ ['delete']|product(info_gtm_topology)|map('join', ' ')|list }}"
  tasks:
    - debug:
        var: payload

As a side note, you can create custom filters. See filter_plugins

shell> cat filter_plugins/list_search.py 
import re


def list_search(l, x):
    r = re.compile(x)
    return list(filter(r.match, l))


def list_index(l, x, *i):
    if len(i) == 0:
        return l.index(x) if x in l else -1
    elif len(i) == 1:
        return l.index(x, i[0]) if x in l[i[0]:] else -1
    else:
        return l.index(x, i[0], i[1]) if x in l[i[0]:i[1]] else -1


class FilterModule(object):
    ''' Ansible filters for operating on lists '''

    def filters(self):
        return {
            'list_index': list_index,
            'list_search': list_search,
        }

The play below

- hosts: localhost
  vars:
    info: ['a', 'gtm topology 1', 'c', 'test-pool1', 'gtm topology 2', 'd']
    stop_regex: '.*pool1.*'
    stop_items: "{{ info|list_search(stop_regex) }}"
    stop_index: "{{ info|list_index(stop_items.0) }}"
    info_gtm_topology: "{{ info[:stop_index|int]|select('search', '^gtm topology') }}"
    payload: "{{ ['delete']|product(info_gtm_topology)|map('join', ' ')|list }}"
  tasks:
    - debug:
        var: payload

gives the same result

payload:
  - delete gtm topology 1
2 of 3
4

You can use the product filter to prefix or suffix items in a list:

---
- hosts: localhost
  gather_facts: false
  vars:
    string: "prepend "
    list: ["value1", "value2", "value3"]
  tasks:
    - name: "prefix"
      set_fact:
        prefix_list: "{{ ["prefix_"] | product(list) | map('join') }}"
    - debug:
        msg: "{{ prefix_list }}"
    - name: "suffix"
      set_fact:
        suffix_list: "{{ list | product(["_suffix"]) | map('join') }}"
    - debug:
        msg: "{{ suffix_list }}"
🌐
Google Groups
groups.google.com › g › ansible-project › c › mSWFXtL7xug
error with appending list in Ansible
list_tunnel: "{{ list_tunnel | default([]) + ['tunnel.' + item | string] }}" loop: "{{ range(1,10) | list}}" - debug: msg: "{{ list_tunnel }}" ... -- You received this message because you are subscribed to the Google Groups "Ansible Project" group. To unsubscribe from this group and stop receiving emails from it, send an email to ansible-proje...@googlegroups.com.
🌐
Ansible
docs.ansible.com › ansible › latest › collections › ansible › builtin › items_lookup.html
ansible.builtin.items lookup – list of items — Ansible Community Documentation
- name: "loop through list" ansible.builtin.debug: msg: "An item: {{ item }}" with_items: - 1 - 2 - 3 - name: add several users ansible.builtin.user: name: "{{ item }}" groups: "wheel" state: present with_items: - testuser1 - testuser2 - name: "loop through list from a variable" ansible.builtin.debug: msg: "An item: {{ item }}" with_items: "{{ somelist }}" - name: more complex items to add several users ansible.builtin.user: name: "{{ item.name }}" uid: "{{ item.uid }}" groups: "{{ item.groups }}" state: present with_items: - { name: testuser1, uid: 1002, groups: "wheel, staff" } - { name: testuser2, uid: 1003, groups: staff }
🌐
GitHub
github.com › ansible › ansible › issues › 17714
Appending or "stacking" variable lists · Issue #17714 · ansible/ansible
September 22, 2016 - ISSUE TYPE Feature Idea COMPONENT NAME Ansible support for appending or "stacking" Variable Lists In this case, with "with_items" --Should be able to append variable lists on the fly, conditionally ANSIBLE VERSION ansible --version ansib...
Author   rahniwalden
🌐
Ansible
forum.ansible.com › get help
Append to list during playbook executions for all hosts - Get Help - Ansible
January 23, 2024 - Hi, I would like to append to a list of dictionaries between the playbook executions for all hosts. However it seems that the list does not retain the appended items. I am using ansible [core 2.13.13]. Here is my playbook: name: “Test” hosts: all_router gather_facts: no vars: backup_status: tasks: name: add items to list set_fact: backup_status: “{{ backup_status + [{‘hostname’: inventory_hostname, ‘status’: ‘Succeeded’}] }}” cacheable: yes delegate_to: localhost name: debug de...
🌐
Medium
medium.com › opsops › how-to-prepend-every-string-in-a-list-with-a-prefix-in-ansible-a6c2bb987046
How to prepend every string in a list with a prefix in Ansible | by George Shuklin | OpsOps | Medium
December 16, 2019 - To simplify our task we will have: hv as imitation of hostvars, and, a list of keys for hv, imitation of groups.groupname. We want to join all foobars from hv with keys from gr, prepending every element with a fixed prefix prefix. ... --- - hosts: localhost gather_facts: false tasks: -set_fact: x: '{{ x|d([]) + [p]|product(hv[item].foo)|map("join")|list }}' with_items: '{{ gr }}' - debug: var=x vars: hv: host1: foobar: - element one - element two junk: - to annoy you host2: foobar: - element 42 host3: foobar: [] junk: to annoy you host4: - should be ignored gr: - host1 - host2 - host3 p: 'The '