How to raise an exception in a Jinja2 macro?

quanta picture quanta · Feb 14, 2014 · Viewed 9.1k times · Source

I have a macro that is used to build a local repository using debmirror.

Here's the snippet of code:

{%- set gnupghome = kwargs.pop('gnupghome', '/root/.gnupg') %}
{%- set env = { 'GNUPGHOME': gnupghome } %}
keyring_import:
  cmd:
    - run
{%- if 'keyid' in kwargs and 'keyserver' in kwargs %}
    {%- set keyid = kwargs.pop('keyid') %}
    {%- set keyserver = kwargs.pop('keyserver') %}
    - name: 'gpg --no-default-keyring --keyring {{ gnupghome }}/trustedkeys.gpg --keyserver {{ keyserver }} --recv-keys {{ keyid }}'
{%- elif 'key_url' in kwargs %}
    {%- set key_url = kwargs.pop('key_url') %}
    - name: 'wget -q -O- "{{ key_url }}" | gpg --no-default-keyring --keyring {{ gnupghome }}/trustedkeys.gpg --import'
{%- endif %}
    - require:
      - pkg: wget
      - pkg: gnupg

At the endif keyword, I would like to use else to raise an exception, for e.g:

Either key_url or both keyserver and keyid required.

Is it possible?

Answer

Lee picture Lee · Mar 25, 2015

Dean Serenevy's answer is elegant. Here is a shorter solution, which adds a global to jinja's environment.

def raise_helper(msg):
    raise Exception(msg)

env = jinja2.Environment(...
env.globals['raise'] = raise_helper

Then in your template:

{{ raise("uh oh...") }}