Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Parse ansible '#jinja2:' overrides #114

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion jinja2cli/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

import os
import sys
import ast
from optparse import Option, OptionParser

sys.path.insert(0, os.getcwd())
Expand Down Expand Up @@ -273,7 +274,26 @@ def render(template_path, data, extensions, strict=False):
env.globals["environ"] = lambda key: force_text(os.environ.get(key))
env.globals["get_context"] = lambda: data

return env.get_template(os.path.basename(template_path)).render(data)
# parse ansible jinja2 overrides
JINJA2_OVERRIDE = '#jinja2:'
with open(template_path, 'r') as f:
template = f.read()
if template.startswith(JINJA2_OVERRIDE):
eol = template.find('\n')
line = template[len(JINJA2_OVERRIDE):eol]
template = template[eol + 1:]
for pair in line.split(','):
if ':' not in pair:
raise RuntimeError("failed to parse jinja2 override '%s'."
" Did you use something different from colon as key-value separator?" % pair.strip())
(key, val) = pair.split(':', 1)
key = key.strip()
if hasattr(env, key):
setattr(env, key, ast.literal_eval(val.strip()))
else:
print(f"Could not find Jinja2 environment setting to override: '{key}'", file=sys.stderr)

return env.from_string(template).render(data)


def is_fd_alive(fd):
Expand Down