Created
January 25, 2023 18:26
-
-
Save ksuderman/82d3d3f91df794439f46842d2dcc07ab to your computer and use it in GitHub Desktop.
Python script to render Jinja2 templates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import os | |
import sys | |
import yaml | |
import argparse | |
from jinja2 import Template | |
from pprint import pprint | |
def render_template(template, values): | |
if not os.path.exists(template): | |
print(f"ERROR: Template not found: {template}") | |
return | |
with open(template, "r") as f: | |
t = Template(f.read()) | |
print(t.render(**values)) | |
if __name__ == "__main__": | |
parser = argparse.ArgumentParser() | |
parser.add_argument("-t", "--template") | |
parser.add_argument("-f", "--values", required=False) | |
parser.add_argument("keyvalues", nargs="*") | |
args = parser.parse_args() | |
if args.template is None: | |
print("ERROR: No template specified") | |
sys.exit() | |
if args.values is None: | |
data = {} | |
else: | |
if not os.path.exists(args.values): | |
print(f"ERROR: values file not found: {args.values} ") | |
sys.exit(1) | |
with open(args.values, "r") as f: | |
data = yaml.safe_load(f) | |
for item in args.keyvalues: | |
key,value = item.split('=') | |
data[key] = value | |
render_template(args.template, data) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment