That's why I quickly went looking to create my own filter plugins. And it's so simple and so powerfull, so I have started to create my own filter plugin libraries, which make my life so much easier.
So lets create one together and see what we can do with it.
What is a filter
A filter in jinja is a function, a piece of code, where you "pipe" variables to, to filter or transform that input.
A few examples : (https://ansible-docs.readthedocs.io/zh/stable-2.0/rst/playbooks_filters.html)
- Filtering arrays
- {{ some_list | max }}
- {{ some_list | unique }}
- Splitting strings or joining arrays
- {{ some_variable | split(',') }}
- {{ some_list | join(',')) }}
- Setting Default values in case of null/undefined
- {{ some_variable | default(5) }}
- Convert data
- {{ some_data | to_json }}
- {{ some_date | to_yaml }}
How to create your own
class FilterModule(object):
def filters(self):
return {
}
def timestamp(pattern):
from datetime import datetime
now = datetime.now()
timestamp = now.strftime(pattern)
return timestamp
print(timestamp("%Y%m%d"))
you can easily test this at https://www.programiz.com/python-programming/online-compiler/
Since we will add this function as a method in the filtermodule class, we will have to add the "self" parameter to the function, like this :
def timestamp(self,pattern):
from datetime import datetime
now = datetime.now()
timestamp = now.strftime(pattern)
return timestamp
class FilterModule(object):
def timestamp(self,pattern):
from datetime import datetime
now = datetime.now()
timestamp = now.strftime(pattern)
return timestamp
def filters(self):
return {
'timestamp':self.timestamp
}
"{{ '%Y%m%d' | timestamp }}"
Note that we don't actually run the filter like "timestamp(pattern)", but rather "pipe" the pattern into the filter.
class FilterModule(object):
'''
creates a timestamp
'''
def timestamp(self,pattern):
from datetime import datetime
now = datetime.now()
timestamp = now.strftime(pattern)
return timestamp
'''
converts a string from ascii to hex
'''
def ascii_to_hex(self,ascii):
return ascii.encode("ascii").hex()
def filters(self):
return {
'timestamp':self.timestamp,
'ascii_to_hex':self.ascii_to_hex
}
What about multiple parameters ?
{{ some_list | join(',') }}
def join(self,list,delimeter):
return list.join(delimeter)
0 Comments