Skip to content

Commit

Permalink
Extend injected render function to accept context
Browse files Browse the repository at this point in the history
The context is merged with original render context before passed on to
salt template engine.
  • Loading branch information
jgraichen committed Feb 25, 2021
1 parent 18eec90 commit a596425
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 4 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
## [Unreleased]
### Added
- Add require option to tower.get
- Experimental: Suppor custom context in template injected `render` function

## [1.5.2] - 2021-02-10
### Fixed
Expand Down
13 changes: 9 additions & 4 deletions salt_tower/pillar/tower.py
Original file line number Diff line number Diff line change
Expand Up @@ -262,16 +262,21 @@ def _compile(
ctx["pillar"] = self
ctx["tower"] = self

def render(path, renderer="text"):
if "basedir" in ctx:
path = os.path.join(ctx["basedir"], path)
def render(path, context=None, renderer='text'):
if isinstance(context, dict):
context = {**ctx, **context}
else:
context = ctx

if "basedir" in context:
path = os.path.join(context["basedir"], path)

file = os.path.abspath(path)

if not os.path.isfile(file):
raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), file)

return self._compile(file, renderer, None, None, ctx)
return self._compile(file, renderer, None, None, context)

ctx["render"] = render

Expand Down
28 changes: 28 additions & 0 deletions test/pillar/test_tower.py
Original file line number Diff line number Diff line change
Expand Up @@ -505,3 +505,31 @@ def test_render_func_in_top(env):
})

assert env.ext_pillar() == {'key': 'This is a test.'}


def test_render_func_context(env):
env.setup({
'tower.sls':
'''
base:
- '*':
- key: !include context/test.py
''',
'context/test.py':
'''
#!py
import os.path
def run():
return context["render"](
os.path.join(context["tmplpath"], "../template.j2"),
context={**context, "message": "Hello World!"}
)
''',
'context/template.j2':
'''
#!jinja|text strip
{{ message }}
''',
})

assert env.ext_pillar() == {'key': 'Hello World!'}

0 comments on commit a596425

Please sign in to comment.