How to Write Custom Ansible Filters?

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!

Senior Software Engineer III ( R&D )

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store