Jinja2 custom filter

Hi,

I’m trying to figure out how I can I use custom jinja2 filters in nornir?

I need to add two custom filters for password encryption, one for username secrets (retrieve from env) and other for BGP key (using passlib hash python library)

In the end, I would like to have something like this in my template

username admin
 group netadmin
 group provisioning
 group root-lr
 group cisco-support
 secret 5 {{ temp | get_from_env('HASHED_PASSWORD') }}

and under BGP neighbor

password encrypted {{ temp | bgp_encrypt(info.key) }}

python code for the filters should look something like this, but can’t figure out yet how to glue things together when I call the template nornir task

import os
from passlib.hash import cisco_type7

def get_from_env(value: str, env_var: str) -> str:
    ret = os.environ.get(env_var)
    if not ret:
        raise Exception("MISSING ENV VARIABLE, PLEASE SET '{}' IN YOUR ENVIORNMENT!".format(env_var))
    return ret


def jinja_filters():
    return {"get_from_env": get_from_env}


def gen_bgp_key(value: str, clear_pass: str) -> str:
    bgp_key = cisco_type7.hash(clear_pass)
    return bgp_key


def bgp_key_filter():
    return {"bgp_key": gen_bgp_key}

I got it working. Just thought on posting it here

import os
from passlib.hash import cisco_type7


def get_from_env(value: str, env_var: str) -> str:
    ret = os.environ.get(env_var)
    if not ret:
        raise Exception("MISSING ENV VARIABLE, PLEASE SET '{}' IN YOUR ENVIORNMENT!".format(env_var))
    return ret


def gen_bgp_key(value: str, clear_pass: str) -> str:
    bgp_key = cisco_type7.hash(clear_pass)
    return bgp_key


def jinja_filters():
    return {"get_from_env": get_from_env, "bgp_key": gen_bgp_key}

And under ini/config.yaml

jinja2:
  filters: autonet_jinja_filters.jinja_filters

on the jinja template

{% if info.key is defined and info.key != None %}
   password encrypted {{ temp | bgp_key(info.key) }}
{% endif %}
1 Like