Syntax

A filter is applied to a variable by way of the pipe symbol |, followed by the name of the filter, and then any arguments for the filter inside parentheses. There can be a space between the variable name and the pipe symbol, as well as a space between the pipe symbol and the filter name. For example, if we wanted to apply the lower filter (which makes all the characters lowercase) to the my_word variable, we would use the following syntax:

{{ my_word | lower }} 

Because the lower filter does not take any arguments, it is not necessary to attach an empty parentheses set to it. If we use a different filter that requires arguments, this all changes. Let's use the replace filter, which allows us to replace all occurrences of a substring with another substring. In this example, we want to replace all occurrences of the substring no with yes in the answers variable:

{{ answers | replace('no', 'yes') }} 

Applying multiple filters is accomplished by simply adding more pipe symbols and more filter names. Let's combine both replace and lower to demonstrate the syntax:

{{ answers | replace('no', 'yes') | lower }} 

We can easily demonstrate this with a simple play that uses the debug command to render the line:

---
- name: demo the template
hosts: localhost
gather_facts: false
vars:
answers: "no so YES no"
tasks:
- name: debug the template
debug:
msg: "{{ answers | replace('no', 'yes') | lower }}"

Now, we can execute the playbook and provide a value for answers at runtime, as shown in the following code:

As we can see here, our variable has had all instances of the word no replaced with yes, and the letters are now all lower case.