How to append to lists in Ansible

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn

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 demonstration playbook and published it on GitHub. See: https://github.com/betrcode/ansible-append-list

How to merge two lists together:

- debug: msg="Append list to list, or merge two lists"

- name: Setup two lists to be merged
  set_fact:
    list_one:
      - 1
      - 2
      - 3
    list_two:
      - 4
      - 5
      - 6

- name: Merge the two lists
  set_fact:
    lists_merged: "{{ list_one }} + {{ list_two }}"

- name: Demonstrate merged lists
  debug: var=lists_merged

The output will be:

TASK [debug] *******************************************************************
ok: [localhost] => {
    "msg": "Append list to list, or merge two lists"
}

TASK [Setup two lists to be merged] ********************************************
ok: [localhost]

TASK [Merge the two lists] *****************************************************
ok: [localhost]

TASK [Demonstrate merged lists] ************************************************
ok: [localhost] => {
    "lists_merged": [
        1, 
        2, 
        3, 
        4, 
        5, 
        6
    ]
}

Appending a single item to a list is trickier, especially when it’s a string. Here’s how to do it:


- name: Initialize an empty list for our strings
  set_fact:
    my_strings: []

- name: Setup a string variable
  set_fact:
    my_name: "Max"

- name: Append string to list
  set_fact:
    my_strings: "{{ my_strings }} + [ '{{ my_name }}' ]"

- debug: var=my_strings

- name: Append another item to the list
  set_fact:
    my_strings: "{{ my_strings }} + [ 'Power' ]"

- debug: var=my_strings

The output will be:

TASK [Initialize an empty list for our strings] ********************************
ok: [localhost]

TASK [Setup a string variable] *************************************************
ok: [localhost]

TASK [Append string to list] ***************************************************
ok: [localhost]

TASK [debug] *******************************************************************
ok: [localhost] => {
    "my_strings": [
        "Max"
    ]
}

TASK [Append another item to the list] *****************************************
ok: [localhost]

TASK [debug] *******************************************************************
ok: [localhost] => {
    "my_strings": [
        "Max", 
        "Power"
    ]
}

More examples can be found at https://github.com/betrcode/ansible-append-list. Happy provisioning!

Leave a Reply

Your email address will not be published. Required fields are marked *