Jinja2 dynamic variables

Just a nice trick. Let’s assume we are using a CSV file and also a YAML file to feed input data to python template.render() function.

In the CSV file, one row is a single Node we would like to generate configuration for. However, some type of variables is easier to maintain in a YAML file. Think about how nice hierarchy we can create.

To connect these two together on the template level we can do something like this: Our input YAML file (globals)

  hostname: cisco

Our input CSV file (node_csv):

10 TESTNODE 7 163

Python template render function:


In Jinja2 we can use the following :

{% set node_name = node_csv.NODE_NAME %}
hostname {{ globals.nodes.get(node_name).hostname }}

The point here is to use the get function to reference a Jinja2 variable inside a variable.

Written on June 25, 2019 in categories: netdev