If you are not familar with arrays, check out Ansible - Getting Started with Array Dictionary List.
Let's say you are using the set_facts module to create an array of strings, like this.
- set_fact:
fruit:
- apple
- banana
- orange
- grape
The debug module can be used to output the entire array, like this.
- name: output the contents of the 'fruit' array
debug:
var: fruit
Which should return the following.
TASK [output the contents of the 'fruit' array]
ok: [server1.example.com] => {
"msg": [
"apple"
"banana",
"orange",
"grapes"
]
}
Here is how you would append another string value to the array.
- name: Append 'plum' to the 'fruit' array
set_fact:
fruit: "{{ fruit }} + ['plum']"
The debug module can be used to output the entire array, like this.
- name: output the contents of the 'fruit' array
debug:
var: fruit
Which should now return the following.
TASK [output the contents of the 'fruit' array]
ok: [server1.example.com] => {
"msg": [
"apple"
"banana",
"orange",
"grapes",
"plum"
]
}
integers
Let's say you are using the set_facts module to create an array of integers.
- set_fact:
integers:
- 1
- 4
- 3
- 5
Here is how you would append another integer value to the array. Notice in this example the 5 is not wrapped in quotes, so that 5 is an integer, not a string.
- name: Append 5 to the 'integers' array
set_fact:
integers: "{{ integers }} + [ 2 ]"
You may want to then sort the array.
- name: Sort the 'integers' array
set_fact:
integers: "{{ integers | sort }}"
with_items
The with_items parameter can be used to loop through something and then append to an array. Notice in this example that single quotes are placed around item. This will result in the item being a string, not an integer.
- name: Append 'items' to the 'fruit' array
set_fact:
fruit: "{{ fruit }} + [ '{{ item}}' ]"
with_items: "{{ out.stdout }}"
Notice in this example that single quotes are not placed around item. This will result in the item being an integer, not a string.
- name: Append 'items' to the 'fruit' array
set_fact:
fruit: "{{ fruit }} + [ {{ item}} ]"
with_items: "{{ out.stdout }}"
The lookup plugin and with_items parameter can be used to append each line in a file on the control node to an array. In this example, each line in the foo.txt file on the control node will be appended to the 'fruit' array.
- name: append each line in foo.txt to the 'fruit' array
set_fact:
fruit: "{{ fruit }} + [ '{{ item }}' ]"
with_items: "{{lookup('file', 'foo.txt') }}"