Skip to content

Instantly share code, notes, and snippets.

@danielmacuare
Last active April 19, 2020 08:19
Show Gist options
  • Save danielmacuare/5c36390e9202538278da418f8506084e to your computer and use it in GitHub Desktop.
Save danielmacuare/5c36390e9202538278da418f8506084e to your computer and use it in GitHub Desktop.
Bolierplate to render an output file from a YAML (Vars) + Jinja (Template)
#!/usr/bin/env python3
import yaml
from jinja2 import Environment, FileSystemLoader, PackageLoader, StrictUndefined
# Docs: https://jinja.palletsprojects.com/en/2.11.x/api/#basics
# Functions
def render_yaml_template(yaml_file, jinja_template, output="files/sshd_config"):
"""
This takes a yam file with all yor vars, a Jinja template and renders an output file
Args:
yaml_file (str): YAML containing the variables neccessary to render the output
jinja_template (str): Jinja template used to render the output
output (str):
Returns:
None
"""
with open(yaml_file, "r") as file:
try:
data = yaml.safe_load(file)
except yaml.YAMLError as err:
print(err)
# print(data)
env = Environment(
loader=FileSystemLoader(searchpath="./templates"),
trim_blocks=True,
lstrip_blocks=True,
undefined=StrictUndefined,
)
try:
template = env.get_template(name=jinja_template)
out_data = template.render(data)
# print(out_data)
with open(output, "w") as file:
file.write(out_data)
except Exception as err:
print(err)
def main():
render_yaml_template(yaml_file="config.yaml", jinja_template="sshd_config.j2")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment