Bootstrap FreeKB - Ansible - Getting Started with Filters
Ansible - Getting Started with Filters

Updated:   |  Ansible articles

Filters are used to modify data. Let's say you are using the set_fact module to create a variable. In this example, the "foo" variable contains a value of "Hello World".

- name: "create the 'foo' variable"
  set_fact: 
    foo: "Hello World"

 

The debug module can be used to print the variable. Notice the double curley braces {{ ... }}. Jinja2 uses double curley braces for variables. 

- name: "output the content of the 'foo' variable"
  debug:
    msg: "{{ foo }}"

 

Which should produce the following.

TASK [output the content of the 'foo' variable]
ok: [server1.example.com] => {
    "msg": "Hello World"
}

 

Notice in this example that foo is wrapped in quotes. When wrapped in quotes, foo is interpreted as a string. If foo were not wrapped in quotes, foo would be interpreted as a variable.

- name: "output the 'foo' string"
  debug:
    msg: "{{ 'foo' }}"

 

Which should produce the following.

TASK [output the 'foo' string]
ok: [server1.example.com] => {
    "msg": "foo"
}

 

Here is how you would use a filter to modify the data. In this example, the regex_replace filter is used to replace Hello with Goodbye in the foo variable.

- name: "output the 'foo' variable, replacing 'Hello' with 'Goodbye'";
  debug:
    msg: "{{ foo | regex_replace('Hello', 'Goodbye') }}"

 

Which should produce the following.

TASK [output the 'foo' variable, replacing 'Hello' with 'Goodbye']
ok: [server1.example.com] => {
    "msg": "Goodbye World"
}

 

Ansible uses the built in Jinja2 filters, as well as filters that are unique to Ansible. Refer to Jinja2 built in filters for the list of filters that are included with Jinja2. regex_search and regex_replace are two example filters that are unique to Ansible, meaning they are not Jinja2 built in filters.




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter b69766 in the box below so that we can be sure you are a human.