In a current project I’m templating files using Jinja2 with the help of the jinja2-cli. Having used (and taught )Ansible for years I’m quite familar with Jinja2 so this was a natural choice.

The jinja2-cli can receive variables to template by different means. One way is by loading them from a file. This can be json, yaml, toml or even xml.

Suppose I have a json-file called payload.json with the following content:

{
"NAME": "bar",
}

And a jinja2-template called template.j2 like this:

hello {{ NAME }}

Then I can run the following command and it prints the templated contents:

> jinja2 template.j2 payload.json
hello bar

Now for some real world example. I have a slightly more complicated configurtion file I need to template. This configuration file already exists and used the normal jinja variable-syntax with {{ and }}.

I need to load the variables from environment variables.

export NAME=bar
export TENANT=tenant
export BASE_DOMAIN=example.com
export HUB_FQDN=hub.example.com

Since the jinja2-cli can also use environment variables, I could change my template to:

hello {{ env(NAME) }}
tenant is {{ env(TENANT) }}
base domain is {{ env(BASE_DOMAIN) }}
hub fqdn is {{ env(HUB_FQDN) }}

This would load the environment variable NAME into the template.

But I don’t want to change my template, so I need to create a payload.json file with the variables that the jinja2-cli can then load.

How should I create this json-file? I could just write it by hand and use normal bash variable substitution. But that’s not very nice.

The go-to tool for handling json on the command line is jq.

I can use jq to create the json-file like this:

> jq -n \
--arg NAME $NAME \
--arg TENANT "$TENANT" \
--arg SSP_BASE_DOMAIN "$SSP_BASE_DOMAIN" \
--arg HUB_FQDN "$HUB_FQDN" \
'$ARGS.named' > payload.json

The cool part about this is $ARGS.named - this takes all arguments and their vales and prints them. I then write the output into the payload.json file.

Now I can export the variables and run the template:

> jinja2 template.j2 payload.json
hello bar
tenant is tenant
base domain is example.com
hub fqdn is hub.example.com

And I’m done!



Related posts: