5

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?

Mikhail T.
  • 2,272
  • 1
  • 22
  • 49
  • 1
    You should write a plugin: https://stackoverflow.com/questions/21778252/how-to-raise-an-exception-in-a-jinja2-macro – Konstantin Suvorov Aug 29 '17 at 15:52
  • Дякую пану. Якщо пан переробить свій коментар на _відповідь_, я її "прийму". – Mikhail T. Aug 29 '17 at 19:08

4 Answers4

3

Ansible adds the mandatory filter to Jinja, which can be used to do this:

{{ ('OK text' if condition_ok) | mandatory('Text of error message') }}

gives the failure:

fatal: [hostname]: FAILED! => {"msg": "Text of error message"}

(Replace condition_ok with the check that you need to make; 'OK text' can be just '' if nothing should be substituted.)

sabik
  • 31
  • 2
  • Didn't work for me, and looking at the [source](https://github.com/ansible/ansible/blob/989eeb243fcf9236bd54d4df60c01f6db4e642a7/lib/ansible/plugins/filter/core.py#L290) it actually checks that the thing passed in is undefined, not just false-y. – lost Sep 28 '21 at 09:25
3

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

Konstantin Suvorov
  • 3,836
  • 1
  • 11
  • 13
1

I have written a jinja2 extension-jinja2_error to raise error.

Firstly,

pip install jinja2_error

If you use it with ansible

ANSIBLE_JINJA2_EXTENSIONS=jinja2_error.ErrorExtension ansible-playbook site.yml -v

If you use it with jinja2 Environment

    from jinja2 import Environment

    from jinja2_error import jinja2_error

    if __name__ == '__main__':
        env = Environment(extensions=[jinja2_error.ErrorExtension])
        render_text = """
                {% if 1==1 %}
                  {% error "It's error" %}
                {% endif %}
                """
        template = env.from_string(render_text)
        result = template.render({"a": "b"})

If you want to know the details, please access

https://github.com/mumubin/jiaja2_error

Dave M
  • 4,494
  • 21
  • 30
  • 30
mumubin
  • 11
  • 1
0

For those who looking for like mandatory filter but not using ansible

{%- if not param.columns %} 
{# use 'include' wrong way, so it raise a error #}
{% include "required 'params.columns' not found!" %}
{%- endif %}
Han-Jong Ko
  • 101
  • 2