Modify list items in Ansible / Jinja2

Another way I found to achieve similar result:

{{ ansible_play_hosts | zip_longest([], fillvalue=':2181')| map('join') | join(',') }}

Looks ugly, but given ansible_play_hosts=['a', 'b'] it produces a:2181,b:2181


... do the trick by creating following two variables in your Role's vars/main.yml file (or at every other place where vars could be defined):

interim_string: "{% for item in myitems %}with-{{item}}X {% endfor %}"
result_list: "{{ interim_string.split() }}"

The resulting result_list now contains following values:

- with-oneX
- with-twoX

Mention the whitespace after the x when defining interim_string. It is used for splitting the interim_string into a list again. You can split by another char or sequence (e.g. split('#')). However this would result in an empty list item at the end of the result_list.


Nowadays the best idiom for this is probably to combine Ansible's map filter with its regex_replace filter. For example, to append -bar to each item in a list:

myitems:
- one
- two
result_list: "{{ myitems | map('regex_replace', '$', '-bar') | list }}"

Which would produce:

result_list:
- one-bar
- two-bar

Or to prepend foo- to each item a list:

myitems:
- one
- two
result_list: "{{ myitems | map('regex_replace', '^', 'foo-') | list }}"

Which would produce:

result_list:
- foo-one
- foo-two

Or to wrap each item in a list with foo- and -bar:

myitems:
- one
- two
result_list: "{{ myitems | map('regex_replace', '(.+)', 'foo-\\1-bar') | list }}"

Which would produce:

result_list:
- foo-one-bar
- foo-two-bar

Tags:

Jinja2

Ansible