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]
else:
return path.split('/')[-2]
---- hosts: localhost
become: false
gather_facts: false
vars:
- p1: /tmp/t1.txt
- p2: /tmp/t2/
- p3: /tmp/t3/t2/t1.txt
tasks:
- debug:
msg: "{{ p1 | lastFolder }}"
- debug:
msg: "{{ p2 | lastFolder }}"
- debug:
msg: "{{ p3 | lastFolder }}"
$ tree .
.
├── filter.yml
└── filter_plugins
└── test.py
1 directory, 2 files

--

--

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

Principal Software Architect I ( R&D DevOps )