join is a Jinja2 filter that can be used to convert a list into a string. Let's say you are using the vars plugin to create an list of fruit. The debug module can be used to output the entire list, like this.
---
- hosts: localhost
gather_facts: false
vars:
fruit:
- apple
- banana
- orange
- grapes
tasks:
- name: debug fruit
debug:
var: fruit
...
Which should return the following which shows that "fruit" is a list.
TASK [debug]
ok: [localhost] => {
"fruit": [
"apple",
"banana",
"orange",
"grapes"
]
}
The join filter can be used to convert the list into a string.
---
- hosts: localhost
gather_facts: false
vars:
fruit:
- apple
- banana
- orange
- grapes
tasks:
- name: debug fruit
debug:
var: fruit | join
...
Which should return the following.
ok: [localhost] => {
"fruit | join": "applebananaorangegrapes"
}
Arguments can be passed into join. In this example, a single white space will be placed between each element.
- debug:
var: fruit | join(' ')
Which should return the following.
ok: [localhost] => {
"fruit | join(' ')": "apple banana orange grapes"
}
Or, as a bit of a more practial example, here is how you could append /tmp/ before a list of files.
---
- hosts: localhost
gather_facts: false
vars:
files:
- foo.txt
- bar.txt
- hello.txt
- world.txt
tasks:
- debug:
msg: "/tmp/{{ files | join(' /tmp/') }}"
...
Which should return the following.
ok: [localhost] => {
"msg": "/tmp/foo.txt /tmp/bar.txt /tmp/hello.txt /tmp/world.txt"
}
And here is how you could use a variable in the join filter.
---
- hosts: localhost
gather_facts: false
vars:
files:
- foo.txt
- bar.txt
- hello.txt
- world.txt
tasks:
- set_fact:
base_directory: "/usr/local/files/"
- debug:
msg: "{{ base_directory }}{{ files | join(' ' + base_directory + '') }}"
...
Which should print the following.
ok: [localhost] => {
"msg": "/usr/local/files/foo.txt /usr/local/files/bar.txt /usr/local/files/hello.txt /usr/local/files/world.txt"
}
Did you find this article helpful?
If so, consider buying me a coffee over at