Skip to content

Commit

Permalink
Parse ansible '#jinja2:' overrides
Browse files Browse the repository at this point in the history
  • Loading branch information
mkhon committed May 11, 2023
1 parent c540c4c commit f85bdc6
Showing 1 changed file with 20 additions and 3 deletions.
23 changes: 20 additions & 3 deletions 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 @@ -246,7 +247,7 @@ def render(template_path, data, extensions, strict=False):
from jinja2 import (
__version__ as jinja_version,
Environment,
FileSystemLoader,
BaseLoader,
StrictUndefined,
)

Expand All @@ -262,7 +263,7 @@ def render(template_path, data, extensions, strict=False):
extensions.append(ext)

env = Environment(
loader=FileSystemLoader(os.path.dirname(template_path)),
loader=BaseLoader(),
extensions=extensions,
keep_trailing_newline=True,
)
Expand All @@ -273,7 +274,23 @@ 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()
setattr(env, key, ast.literal_eval(val.strip()))

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


def is_fd_alive(fd):
Expand Down

0 comments on commit f85bdc6

Please sign in to comment.