Skip to content

Instantly share code, notes, and snippets.

@elliot-u410
Created September 23, 2021 20:56
Show Gist options
  • Save elliot-u410/656c8d0dce8e53b90190aad725f331a6 to your computer and use it in GitHub Desktop.
Save elliot-u410/656c8d0dce8e53b90190aad725f331a6 to your computer and use it in GitHub Desktop.
mapfunc Ansible Filter Plugin
#!/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)
@elliot-u410
Copy link
Author

To use: Save this file in a folder called filter_plugins sibling to your playbooks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment