After completing this section, you should be able to:
Reformat the data in a variable with a Jinja2 filter.
Run a task conditionally based on the result of a Jinja2 test.
Filters in Ansible are from Jinja2, and are used for transforming data inside a template expression.
Filters are available for a wide variety of use cases.
For example, to transform the CIDR form of an IPv4 address into a host address, you can use the ipaddr filter:
{{ '192.0.2.1/24' | ipaddr('address') }}
This returns the value 192.0.2.1.
You can use the same Jinja2 filter with a different argument to extract the variable-length subnet mask from that specification:
{{ '192.0.2.1/24' | ipaddr('netmask') }}
This returns the value 255.255.255.0.
You can use the prefix argument with the ipaddr filter if you want the CIDR prefix for that subnet mask instead.
A network CLI filter is available that, when used in conjunction with a parser specification, automatically parses a network device CLI command output into structured JSON form.
---
- name: a play that shows parsed interface data
hosts: ios
gather_facts: no
vars:
shint_parser: vars/ios-shipintbr-parser.yml
tasks:
- name: issue commands
ios_command:
commands:
- show ip interface brief
register: results
- name: show CLI output
debug:
msg: "{{ results.stdout[0] | parse_cli(shint_parser) }}"Jinja2 tests evaluate template expressions and return a True or False result.
You can use these expressions to conditionally run tasks.
The when directive only runs a task if its condition or list of conditions are True.
tasks:
- name: run a command
vyos_command:
commands:
- show interface ethernet eth2
register: result
ignore_errors: True
- debug:
msg: "show interface ethernet eth2 failed, interface might not be present"
when: result is failed
In this example, the expression result is failed is a Jinja2 test.