Language style guides

Jinja templating language

Notation

Use dot notation:

{{ pillar.host_id }}
{{ grains.kernel }}

AVOID bracket notation:

{{ pillar['host_id'] }}  # AVOID
{{ grains['kernel'] }}  # AVOID

Note

To allow the use of dot notation in Jinja, prefer underscores to hyphens in Pillar keys.

Concatenation

To concatenate strings, use the ~ operator, which converts its operands to strings:

{% set userdir = '/home/' ~ user %}

AVOID the + operator, which is for numbers and lists:

{% set userdir = '/home/' + user %}  # AVOID

Note

Maintainers can check this style rule with this regular expression:

\+ ['"]|['"] \+

Optional boolean keys

To test whether an optional boolean is true, use the .get() method:

{% if pillar.parent.get('enabled') %}

Add a new boolean key to the regular expression under Optional mapping keys.

Optional mapping keys

To test whether a non-boolean key is present in a mapping, use the in operator:

{% if 'child' in pillar.parent %}

Note

Maintainers can check this style rule with this regular expression, which excludes boolean keys:

if .*get\(.(?!(?:ENABLE_CHECKER|autoremove|cardinal|enabled|filter|public_access|replication|reports|scrapyd_norestart|site_logs|smartmon|summarystats|syslog_logging|write)\b)

To iterate over an optional mapping:

{% for key, value in pillar.mykey|items %}

Or:

{% for key, value in salt['pillar.get']('parent:child', {})|items %}

Note

Maintainers can check this style rule with this regular expression:

\bif\b.*\n.*%.*\bfor\b

Optional list keys

To iterate over an optional list:

{% for value in pillar.mykey|default([]) %}

Or:

{% for value in salt['pillar.get']('parent:child', []) %}

Optional keys

To get an optional key with a default value:

{{ entry.mykey|default(123) }}

If the default value is the empty string:

{{ entry.mykey|default }}

Note

Maintainers can check this style rule with this regular expression:

(?<!salt\['pillar)\.get\([^\s-]+,

If many parts of a Pillar key might not be set, use salt['pillar.get']():

{{ salt['pillar.get']('parent:child') }}

Note the colon (:) between parent and child.

YAML data-serialization language

Capitalize the True and False booleans, for consistency.

Avoid gotchas

  • If unquoted, yes, no, True and False are parsed as booleans in YAML. Use quotes to parse as strings.

  • A blank value is parsed as None in YAML. Use the empty string '' to parse as a string.

For example, in the Jinja snippet below, if a is equal to an empty string, then b will be None:

{% set extracontext %}
b: {{ a }}
{% endset %}

Instead, surround it in quotes:

{% set extracontext %}
b: "{{ a }}"
{% endset %}