Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to raise an exception in a Jinja2 macro?

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?

like image 931
quanta Avatar asked Feb 14 '14 11:02

quanta


People also ask

What is a Jinja2 macro?

July 20, 2021. Jinja2 is a popular text templating engine for Python that is also used heavily with Ansible. Many network engineers are familiar with it and with leveraging Jinja2 templates for device configurations.

What is Autoescape in Jinja2?

B701: Test for not auto escaping in jinja2When autoescaping is enabled, Jinja2 will filter input strings to escape any HTML content submitted via template variables. Without escaping HTML input the application becomes vulnerable to Cross Site Scripting (XSS) attacks. Unfortunately, autoescaping is False by default.

How do you write a for loop in Jinja2?

Jinja2 being a templating language has no need for wide choice of loop types so we only get for loop. For loops start with {% for my_item in my_collection %} and end with {% endfor %} . This is very similar to how you'd loop over an iterable in Python.


1 Answers

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...") }}
like image 81
Lee Avatar answered Oct 13 '22 13:10

Lee