How to Write Custom Ansible Filters?

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]
---- 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 }}"
$ tree .
├── filter.yml
└── filter_plugins
1 directory, 2 files




Senior Software Engineer III ( R&D )

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Miner — Blog Framework based on Sapper/Svelte

I have gotten access to test out Github Copilot BUT!

A beginner’s guide to Linux command-line

How to effortlessly create a free portfolio and blog

Full Stack Pronounced Dead

CS373 Spring 2022: Shreya Sridhar

How I prepared & passed the Certified Kubernetes Administrator (CKA) Exam

How To Get Live And Historical 9K Gold Rates Using API?

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
Davinder Pal

Davinder Pal

Senior Software Engineer III ( R&D )

More from Medium

How to install Apache Web Server on Ubuntu Linux

GitLab CD Pipeline for Linux package management

NGINX monitoring commands

Drop a PostgreSQL Database — Ansible module postgresql_db