You can use Ansible filters when you need to format data inside template expressions. You are provided with a set of filters that are shipped with Ansible and another set provided by Jinja2 template engine. You can also build your own filters.

In the following sections, I will give a list of useful filters and their examples.

## Ansible math filters

#### Absolute value of a number

The **abs **filter is used to get the absolute value of a number. In the following example, it used to get the absolute value of (-5.5 * 7). Remember to put the bracket around the multiplication operation. Else you will get “-38.5”.

- hosts: all vars: number: -5.5 tasks: - name: Ansible abs math filter example debug: var: (number * 7) |abs

#### Converting to integer value

The **int** filter is used to get the integer value of a decimal.

- hosts: all vars: number: -8.35 tasks: - name: Ansible int filter example debug: var: (number * 3.6) | int

Output = “-30”

#### Calculating the power of a number in Ansible

Calculating power or exponential of a number is possible using Ansible arithmetic operation. They have provided a ‘pow’ filter for the same.

The following example gives the value of 3^3 which is 27.

- hosts: all tasks: - name: Ansible arithemtic power filter example debug: msg: "{{ 3|pow(3)}}"

#### Calculating the root of numbers in Ansible

You can get the root of an umber in a similar manner using the root filter. The following example gives the cube root of 27 which is 3.

- hosts: all tasks: - name: Ansible math power filter example debug: msg: "{{ 27|root(3)}}"

#### Ansible round examples with jinja2 filters

You can round a given to the precision you want using the ’round’ jinja2 filter. You can either round up or down specifically, or the default round operation is also possible.

- hosts: all tasks: - name: Ansible round filter example - output 30 debug: msg: "{{ 29.7 | round}}" - name: Ansible round number with precision specified example - output 29.1 debug: msg: "{{ 29.094 | round(1,'common')}}" - name: Floor round operation with precision example - output 29.0 debug: msg: "{{ 29.094 | round(1,'floor')}}" - name: Ceil round operation with precision specified example - output 29.1 debug: msg: "{{ 29.094 | round(1,'ceil')}}"