Here is an example code from an SLS (salt stack) file, using Jinja:
{% set here = 'some-value' -%}
{%- set user = 'my_user' -%}
{%- set group = 'my_group' -%}
{%- set all_users = salt['user.list_users']() -%}
{%- if user in all_users -%}
{%- set usr_home = salt['user.info'](user).home -%}
{%- set prefix = 'some_prefix' ~ '_' ~ user %}
# This is just an example state
{{ prefix }}-dotvnc:
file.directory:
- name: {{ usr_home }}/.vnc
- user: {{ user }}
- group: {{ group }}
- mode: '0700'
{% endif -%}
This looks very ugly, I would like to do something like this:
{%
set here = 'some-value'
set user = 'my_user'
set group = 'my_group'
set all_users = salt['user.list_users']()
if user in all_users
set usr_home = salt['user.info'](user).home
set prefix = 'some_prefix' ~ '_' ~ user
%}
# This is just an example state
{{ prefix }}-dotvnc:
file.directory:
- name: {{ usr_home }}/.vnc
- user: {{ user }}
- group: {{ group }}
- mode: '0700'
{% endif -%}
Multiple variables and commands cannot be avoided, this example shows a template that uses the home directory of a user from Jinja, but, the user may not exists when the template is rendered, and so its home directory may not exist.
While the first version works, it is very ugly, and hard to read.
Is there way to make this less cryptic?
This is not a duplicate of Code blocks in Jinja templates in salt, because dictionary lookups cannot be used in this case. E.g. the code is arbitrary.
One alternative syntax you could use is the line statement one — but if it is less cryptic or not is, off course, to your liking.
With it, your template could look like this:
% set user = 'my_user'
% set group = 'my_group'
% set all_users = salt['user.list_users']()
% if user in all_users
% set usr_home = salt['user.info'](user).home
% set prefix = 'some_prefix' ~ '_' ~ user
# This is just an example state
{{ prefix }}-dotvnc:
file.directory:
- name: {{ usr_home }}/.vnc
- user: {{ user }}
- group: {{ group }}
- mode: '0700'
% endif
Which would render to something like
some_prefix_my_user-dotvnc:
file.directory:
- name: /home/my_user/.vnc
- user: my_user
- group: my_group
- mode: '0700'
This possibility is offered via the parameters line_statement_prefix
and line_comment_prefix
.
jinja_env
and jinja_sls_env
.jinja_sls_env:
line_statement_prefix: '%'
line_comment_prefix: '#'
#jinja2:line_statement_prefix: '%', line_comment_prefix: '#'
% set user = 'my_user'
# ... the rest of the template goes here
from jinja2 import Environment, PackageLoader, select_autoescape
env = Environment(
loader=PackageLoader("yourapp"),
line_statement_prefix='%',
line_comment_prefix='#'
)