Created
September 23, 2021 20:56
-
-
Save elliot-u410/656c8d0dce8e53b90190aad725f331a6 to your computer and use it in GitHub Desktop.
mapfunc Ansible Filter Plugin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
class FilterModule(object): | |
def filters(self): | |
return { | |
'mapfunc': self.mapfunc, | |
'applyfunc': self.applyfunc, | |
} | |
def mapfunc(self, items, func_expr_str, *static_args, **static_kwargs): | |
"""Map a Python function over all the inputs. | |
For example, {{ ["a", "b"] | mapfunc("lambda x: x.upper()") }} | |
produces ["A", "B"] | |
Positional and keyword arguments passed to the filter will propagate to each iteration: | |
{{ ["a", "b"] | mapfunc("lambda x, replace: replace", replace="X") }} | |
produces | |
["X", "X"] | |
""" | |
func = eval(func_expr_str, {}, {}) | |
return (func(x, *static_args, **static_kwargs) for x in items) | |
def applyfunc(self, item, func_expr_str, *static_args, **static_kwargs): | |
""" | |
Apply a Python function to the input. | |
For example, {{ ["c", "d"] | applyfunc("lambda xs: map(str.upper, xs)") }} | |
produces ["C", "D"] | |
Positional and keyword arguments passed to the filter will be passed as arguments to the function: | |
{{ ["a", "b"] | applyfunc("lambda x, replace: replace", replace="X") }} | |
produces | |
"X" | |
""" | |
func = eval(func_expr_str, {}, {}) | |
return func(item, *static_args, **static_kwargs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To use: Save this file in a folder called
filter_plugins
sibling to your playbooks.