j2cli — Templating Shell Scripts

j2cli is a simple but awesome tool that provides an easy way to template shell scripts, it uses jinja2 as a templating engine

j2cli is a simple but awesome tool that provides an easy way to template shell scripts, it uses jinja2 as a templating engine$ sudo pip install j2cli

j2cli supports templating from various sources like

  • INI files
  • JSON
  • Environment Variables
  • YAML

I will not provide examples on how to use the various template sources, since excellent documentation can be found at the projects homepage: https://github.com/kolypto/j2cli

Instead i will provide an example with good practices on How to temporary modify some configuration file parameters using environment variables just before execution, this can be considered as way to convert a tool that does not accept command line arguments, but only a configuration file to a flexible tool that accepts command line arguments.

Scenario: The program we use accepts username and password in configuration file and requires each user to modify the contents of the file before they use it, plus that its a security risk, someone might forget to delete his password after using the tool, the configuration file (myconf.ini) has the following format[CREDENTIALS]
USER: myusername
PASS: mypassword

Solution:

  • Copy myconf.ini to myconf.j2$ cp myconf.ini myconf.j2
  • Edit myconf.j2 and replace myusername and mypassword to {{ username }} and {{ password }} respectively[CREDENTIALS]
    USER: {{ username }}
    PASS: {{ password }}

Create the following bash script and save it as wrapper.sh#!/bin/bash# Get command line arguments -u <username> -p <password>
while getopts ":u:p:" opt; do
  case $opt in
    u) export username="$OPTARG"
    ;;
    p) export password="$OPTARG"
    ;;
    \?) echo "Invalid option -$OPTARG" >&2
    ;;
  esac
done# Create the configuration file from the template
j2 myconf.j2 > myconf.cfg# unset the variables
unset username
unset password# Execute the program that uses the configuration we just created
# from the template
myprogram --configration myconf.cfg# Delete the configuration
rm -f myconf.cfg

Make wrapper.sh executable$ chmod +x wrapper.sh

What this wrapper does:

  1. Gets the command line arguments from shell as environment variables
  2. j2 uses those environment variables to create a new configuration from the myconf.j2 template
  3. Unset the environment variables
  4. run the program that uses the configuration
  5. delete the configuration file after program execution

I hope you found this article useful :)

Join Medium with my referral link - Konstantinos Patronas
As a Medium member, a portion of your membership fee goes to writers you read, and you get full access to every story…