Modify All Items in Ansible List

Ansible lets you easily interpolate list items within values (like interpolated_{{ item }}_value). However, sometimes you need a more powerful transformation. This is where the map filter comes to rescue again. You can use it to perform regular expression replace on each item in a list. As you can see, the syntax is relatively simple:

map('regex_replace', REGEX_PATTERN, OUTPUT)

For a concrete example, let us say you want to extract network mask from a list of IP addresses ( for example). Assuming this list is stored in the ip_addresses variable, the regex replace would look like this:

{{ ip_addresses | map('regex_replace', '.*/([0-9]{1,2})', '\\1') | list }}

Of course, you can easily use it as a part of longer jinja2 pipelines. If you also want to learn how to loop over dictionary attribute, or see other Ansible tips, take a look here.