Friday, August 4, 2017

Ansible Filters

Filters in Ansible are from Jinja2, and are used to do some filter operations with variable and with other items also.

Below are some of the filters with example.

1) Mandatory

When we use this setting and if the variable is not set then we will get the error like mentioned below.

---
 - hosts: ss
   tasks:
   - name: Check Mandotry filter setting
     debug: msg={{ variable | mandatory }}
...

Result:
FAILED! => {"failed": true, "msg": "Mandatory variable not defined."}

2) Default filter

{{ variable1 | default(56) }}

When this setting is used and if the variable is not set then the value of the variable will be replaced with the default value mentioned int the filter rather than the error being raised.

3) Default with Omit module

If we leave default filter value as NULL it will cause the chain of filters like “{{ variable | default(None) | Second_filter or omit }}” to fail. So it is better to have the value as omit if the value is NULL.

In the result we can see that only for file INDIA we have permission 444 for others where mode value is not set in the variable declaration section it took the default permission.

---
 - hosts: ss
   tasks:
   - name: Test Default filter with omit module
     file: dest={{item.path}} state=touch mode={{item.mode|default(omit)}}
     with_items:
     - path: /tmp/I
     - path: /tmp/LOVE
     - path: /tmp/INDIA
       mode: "0444"
...

-rw-------  1 moham607 users          0 Jul 18 06:21 I
-rw-------  1 moham607 users          0 Jul 18 06:21 LOVE

-r--r--r--  1 moham607 users          0 Jul 18 06:21 INDIA

4) Using IP filter 

Use IP filter to check is the variable value is a valid IP v4 address or not. But to use this filter we need python-netaddr package to be installed.

{{ myIP | ipaddr }}
{{ myIP | ipv4 }}
{{ myIP | ipv6 }}

---
 - hosts: ss
   tasks:
     - name: Take the IP of server using facts and check with the help of IP filter and print
       debug: msg="IP address of server is {{facter_ipaddress_eth2}}"
       when: (facter_ipaddress_eth2 | ipv4)
      (or)
      when: (ansible_eth3.ipv4.address | ipv4)
...


Above Task will print the message with IP address when the value of facter_ipaddress_eth2 is a valid ipv4 IP address.

No comments:

Post a Comment