Though Ansible itself has a way for triggering a custom error, I can not find anything similar for Jinja.
My current method uses a syntax error:
{% if 'ansible_mounts' in hostvars[host] %}
# {{ host }} knows its mount-points
{% else %}
# {% error!! No ansible_mounts listed for host - fact-gathering must've failed %}
{% endif %}
but those are rendered poorly at run-time -- one needs to look inside the template-file and search for the error (the rendering does not even include the line-number!).
Is there a way to output a neat failure message from inside Jinja-template?
Answer from the comment:
There is no easy way to accomplish this – only via custom plugin. For details see: https://stackoverflow.com/questions/21778252/how-to-raise-an-exception-in-a-jinja2-macro
Ansible adds the mandatory filter to Jinja, which can be used to do this:
gives the failure:
(Replace
condition_ok
with the check that you need to make;'OK text'
can be just''
if nothing should be substituted.)I have written a jinja2 extension-jinja2_error to raise error.
Firstly,
If you use it with ansible
If you use it with jinja2 Environment
If you want to know the details, please access
https://github.com/mumubin/jiaja2_error
For those who looking for like mandatory filter but not using ansible