Filter plugins

While Jinja2 includes a number of filters, Ansible has made filters pluggable to extend the Jinja2 functionality. Ansible includes a number of filters that are useful for Ansible operations, and users of Ansible can add more. Existing plugins can be found in plugins/filter/.

To demonstrate the development of a filter plugin, we will create a simple filter plugin to do a silly thing to text strings. We will create a filter that will replace any occurrence of the words the cloud with the string somebody else's computer. We'll define our filter in a file within a new directory, filter_plugins/, in our existing working directory. The name of the file doesn't matter, as we'll define the name of the filter within the file; so, let's name our file filter_plugins/sample_filter.py.

First, we need to define the function that will perform the translation, and provide the code to translate the strings:

def cloud_truth(a): 
    return a.replace("the cloud", "somebody else's computer") 

Next, we'll need to construct a FilterModule object and define our filter within it. This object is what Ansible will load, and Ansible expects there to be a filters function within the object that returns a set of filter names to functions within the file:

class FilterModule(object): 
    '''Cloud truth filters''' 
    def filters(self): 
        return {'cloud_truth': cloud_truth} 

Now we can use this filter in a playbook, which we'll call simple_filter.yaml:

--- 
- name: test cloud_truth filter 
  hosts: localhost 
  gather_facts: false 
  vars: 
    statement: "I store my files in the cloud" 
  tasks: 
  - name: make a statement 
    debug: 
      msg: "{{ statement | cloud_truth }}" 

Now, let's run our playbook and see our filter in action:

Our filter worked, and it turned the words the cloud into somebody else's computer. This is a silly example without any error handling, but it clearly demonstrates our capability to extend Ansible and Jinja2's filter capabilities.

Although the name of the file containing a filter definition can be whatever the developer wants, a best practice is to name it after the filter itself so that it can easily be found in the future, potentially by other collaborators. This example did not follow this, to demonstrate that the file name is not attached to the filter name.