Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify list items in Ansible / Jinja2

Tags:

ansible

jinja2

For instance you have a list variable in your role...

myitems:
  - one
  - two

... and want to modify each item within Ansible (e.g. append a string before/after), you can...

like image 620
Thomas Steinbach Avatar asked Feb 01 '16 23:02

Thomas Steinbach


1 Answers

... 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.

like image 128
Thomas Steinbach Avatar answered Sep 27 '22 20:09

Thomas Steinbach