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?
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.
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.
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.
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...") }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With