Add assert filter #22529
Add assert filter #22529
Conversation
how is this different than the |
The |
That sounds more like a "test" and not a filter. Also I am against calling it assert, as that will cause confusion with the assert module. |
@sivel you're right about the name clash. The filter is something like the assert module, but "inline". I explicitly called it "assert", not "test" (or similar) because assertions are known to fail and stop the whole program if the expression isn't true, while e.g. Any name suggestions? |
I think that the mandatory filter should just be updated to support this. Using a kwarg, that activates this functionality. Just like the Something like: diff --git a/lib/ansible/plugins/filter/core.py b/lib/ansible/plugins/filter/core.py
index f109c3e..ad79f0a 100644
--- a/lib/ansible/plugins/filter/core.py
+++ b/lib/ansible/plugins/filter/core.py
@@ -278,11 +278,11 @@ def get_encrypted_password(password, hashtype='sha512', salt=None):
def to_uuid(string):
return str(uuid.uuid5(UUID_NAMESPACE_ANSIBLE, str(string)))
-def mandatory(a):
+def mandatory(a, boolean=False):
from jinja2.runtime import Undefined
''' Make a variable mandatory '''
- if isinstance(a, Undefined):
+ if isinstance(value, Undefined) or (boolean and not value):
raise errors.AnsibleFilterError('Mandatory variable not defined.')
return a |
My use case is to create a filter that explicitly has no output, but only does validation. Therefore it can accept any bool-testable expression without inserting the result into the text (I guess you don't want |
Yeah, I will say I don't like your approach in the slightest. In my view the filter should:
It shouldn't just be a magical thing you stick somewhere. So it should work like:
Where it either fails, or returns the contents of However, the more I think about it, the more I think you should just use the
|
Fair points. If you don't see it in core, then I have to be fine with that. Using |
SUMMARY
Introduces a new Jinja template filter
assert
to fail on falsy expression or otherwise resolve to nothing (empty string).ISSUE TYPE
COMPONENT NAME
assert [new filter plugin]
ANSIBLE VERSION
ADDITIONAL INFORMATION
Example use case (there are many others): for a missing dict key, Ansible doesn't give great error messages nor location, and even if it did, you may want to provide your own error message.
Usage:
On successful assertion, the filter resolves to an empty string for obvious reasons.
Output: