How to Write Custom Ansible Filters?

Davinder Pal
1 min readSep 12, 2020

let’s talk a bit about ansible filters.

A Simple Function or Set of Functions can transform a given input into the desired output.

Ansible Docs:

Create a folder called: filter_plugins

Create a .py file with any name: with the below content.

import osclass FilterModule(object):
def filters(self):
return {'lastFolder': self.lastFolder}
def lastFolder(self, path):
if os.path.isdir(path):
return path.split('/')[-1]
return path.split('/')[-2]

please do keep in mind that Class Name & method filters should be there as exactly mentioned above otherwise it won’t work.

Create Sample Playbook to Test it: filter.yml

---- hosts: localhost
become: false
gather_facts: false
- p1: /tmp/t1.txt
- p2: /tmp/t2/
- p3: /tmp/t3/t2/t1.txt
- debug:
msg: "{{ p1 | lastFolder }}"
- debug:
msg: "{{ p2 | lastFolder }}"
- debug:
msg: "{{ p3 | lastFolder }}"

Output from Playbook

Sample Structure of Folder

$ tree .
├── filter.yml
└── filter_plugins
1 directory, 2 files

It is quite amazing that you can run native python 3 code for something if ansible can’t support it.

Hopefully, It will help you in the worse case!