Table of contents
1.
Introduction
2.
Jinja in States 
3.
Include and Import 
4.
Macros 
5.
Template Inheritance 
6.
Errors 
7.
Filters 
7.1.
EXACTLY_ONE_TRUE
7.2.
QUOTE
7.3.
REGEX_SEARCH
7.4.
REGEX_MATCH
7.5.
REGEX_REPLACE
7.6.
UUID
7.7.
IS_LIST
7.8.
IS_ITER
7.9.
MIN
7.10.
MAX
7.11.
AVG
7.12.
UNION
7.13.
INTERSECT
7.14.
DIFFERENCE
7.15.
SYMMETRIC_DIFFERENCE
7.16.
IS_SORTED
7.17.
COMPARE_LISTS 
7.18.
COMPARE_DICTS 
7.19.
IS_HEX 
7.20.
CONTAINS_WHITESPACES 
7.21.
SUBSTRING_IN_LIST 
7.22.
DATE_FORMAT 
7.23.
TO_NUM
7.24.
TO_BYTES
7.25.
JSON_ENCODE_LIST 
7.26.
JSON_ENCODE_DICT 
7.27.
RANDOM_HASH
7.28.
RANDOM_SAMPLE
7.29.
RANDOM_SHUFFLE 
7.30.
SET_DICT_KEY_VALUE 
7.31.
MD5
7.32.
SHA256
7.33.
SHA512 
7.34.
BASE64_ENCODE
7.35.
HMAC 
7.36.
Http_Query 
7.37.
TRAVERSE
7.38.
Json_Query
7.39.
TO_SNAKE_CASE
7.40.
TO_CAMELCASE
7.41.
HUMAN_TO_BYTES
7.42.
STRFTIME 
7.43.
SEQUENCE
7.44.
YAML_ENCODE 
7.45.
YAML_DQUOTE
7.46.
YAML_SQUOTE
7.47.
DICT_TO_SLS_YAML_PARAMS
7.48.
TO_BOOL
7.49.
FLATTEN
7.50.
COMBINATIONS 
7.51.
COMBINATIONS_WITH_REPLACEMENT
7.52.
COMPRESS
7.53.
PERMUTATIONS 
7.54.
PRODUCT 
7.55.
ZIP 
7.56.
ZIP_LONGEST 
7.57.
METHOD_CALL 
7.58.
CHECK_WHITELIST_BLACKLIST
7.59.
TOJSON 
7.60.
Networking Filters 
7.61.
IS_IP 
7.62.
IS_IPV4
7.63.
IS_IPV6
7.64.
IPADDR
7.65.
IPV4 
7.66.
IPV6 
7.67.
Network_Hosts 
7.68.
Network_Size 
7.69.
Gen_Mac 
7.70.
MAC_TO_STR_BYTES
7.71.
DNS_CHECK
8.
File Filters 
8.1.
IS_TEXT_FILE 
8.2.
IS_BINARY_FILE 
8.3.
IS_EMPTY_FILE 
8.4.
FILE_HASHSUM  
8.5.
List_Files  
8.6.
Path_Join 
8.7.
WHICH 
9.
Tests 
9.1.
EQUAL TO
9.2.
MATCH 
10.
Escape Filters 
10.1.
Regex_Escape 
11.
Frequently Asked Questions
11.1.
What is saltstack?
11.2.
Where do we use saltstack?
11.3.
Is saltstack still free of cost to developers?
11.4.
What is SaltStack's drawback? 
11.5.
What is the advantage of saltstack? 
12.
Conclusion
Last Updated: Mar 27, 2024
Medium

About Jinja in Salt

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Any text-based format, including HTML, XML, and YAML, can be created using the Python templating language Jinja. You can insert data in a structured manner using languages that provide templates, such as Jinja. For increased reuse and modularity, logic or control-flow statements can also be incorporated into templates. The code contained in the templates is processed by Jinja's template engine, which also creates the output for the finished text-based content.

Jinja in salt-title

In the context of developing web pages using a Model View Controller architecture, templating languages are well recognized. This article will give a general overview of the Salt-specific Jinja templating language. 

Jinja in States 

Since Jinja is evaluated before YAML, it precedes the execution of the States. The most fundamental application of Jinja in state files is the use of control structures to enclose duplicate or conditional state components:

{% if grains['os'] != 'FreeBSD' %}
tcsh:
    pkg:
        - installed
{% endif %}


motd:

file.managed:
    {% if grains['os'] == 'FreeBSD' %}
    - name: /etc/motd
    {% elif grains['os'] == 'Debian' %}
    - name: /etc/motd.tail
    {% endif %}
    - source: salt://motd


The first if block in this example will only be applied to slaves that aren't running FreeBSD, and the second block modifies the file name according to the operating system.

However, writing if-else blocks can result in highly redundant state files. In this situation, it might be simpler to use pillars or a previously defined variable: 

{% set motd = ['/etc/motd'] %}
{% if grains['os'] == 'Ubantu' %}
  {% set motd = ['/etc/motd.tail', '/var/run/motd'] %}
{% endif %}
{% for motdfile in motd %}
{{ motdfile }}:
  file.managed:
    - source: salt://motd
{% endfor %}


The for loop will traverse over the list of MOTD files to update, adding a state block for each file using a variable set by the template.

Variables based on grains can also be set using the filter by function:

{% set auditd = salt['grains.filter_by']({
'RedHat': { 'package': 'audit' },
'Debian': { 'package': 'auditd' },
}) %} 

Include and Import 

To exchange reusable state configuration between state files and between files, includes and imports can be used.

{% from 'lib.sls' import test %}


Instead of importing the test state element, this would import the macro or test template variable from the lib.sls file. Passing the context into the selected file is necessary if it performs checks against grains or does anything else that needs context:

{% from 'lib.sls' import test with context %}


Includes must use complete paths, as follows:

{% include 'spam/foobar.jinja' %}

Macros 

Macros help remove unnecessary code. The best uses for macros are to repeat strings in blocks using a few parameterized variables. To simulate a variable return from the macro, we note that the template block and any contained blocks may need to be stripped of all whitespace.

# init.sls
{% from 'lib.sls' import pythonpkg with context %}

python-virtualenv:
  pkg.installed:
    - name: {{ pythonpkg('virtualenv') }}

python-fabric:
  pkg.installed:
    - name: {{ pythonpkg('fabric') }}

# lib.sls
{% macro pythonpkg(pkg) -%}
  {%- if grains['os'] == 'FreeBSD' -%}
    py27-{{ pkg }}
  {%- elif grains['os'] == 'Debian' -%}
    python-{{ pkg }}
  {%- endif -%}
{%- endmacro %}


Depending on the makepackaging system's naming convention, this would be a macro that would return a string containing the full package name. Using whitespace control, the macro's whitespace was removed to return a string devoid of line breaks.

Template Inheritance 

From state files and files, template inheritance functions as intended. The state tree's or pillar's root is where the search path begins. 

Errors 

Using the raise jinja function, Saltstack enables the raising of unique errors.

{{ raise('Custom Error') }}


The rendering of the template containing the preceding statement fails due to a TemplateError exception, which raises the following message:

TemplateError: Custom Error

Filters 

With these additional custom filters, Saltstack expands built-in filters: 

EXACTLY_ONE_TRUE

Definition  Checks that just one iterable item is "truthy" (neither None, False, nor 0). 
Example {{ ['yes', False, 0, None] | exactly_one_true }}
Returns True 

QUOTE

There will be quotes around this text.

REGEX_SEARCH

Definition  Look for a spot in the string where this regular expression returns a match by scanning it. Returns None in case no matches were discovered. 
Example {{ 'abcdefabcdef' | regex_search('BC(.*)', ignorecase=True) }}
Returns ("defabcdef",)

REGEX_MATCH

Definition  Returns True if the string's first few characters match this regular expression; otherwise, it returns False. 
Example {{ 'abcdefabcdef' | regex_match('BC(.*)', ignorecase=True) }}
Returns None

REGEX_REPLACE

Definition  Finds a pattern, then replaces it with a string of characters.
Example

{% set my_text = 'yes, this is a TEST' %}

{{ my_text | regex_replace(' ([a-z])', '__\\1', ignorecase=True) }}

Returns yes,__this__is__a__TEST

UUID

Definition  Give back a UUID.
Example {{ 'random' | uuid }}
Returns 3652b285-26ad-588e-a5dc-c2ee65edc804

IS_LIST

Definition  It checks if an object is a list.
Example {{ [1, 2, 3] | is_list }}
Returns True

IS_ITER

Definition  If an object is iterable, return true.
Example {{ [1, 2, 3] | is_iter }}
Returns True

MIN

Definition  Get the lowest value possible from a list.
Example {{ [1, 2, 3] | min }}
Returns 1

MAX

Definition  A list's maximum value is returned.
Example {{ [1, 2, 3] | max }}
Returns 3

AVG

Definition  It Returns the list's average value for each element.
Example {{ [1, 2, 3] | avg}}
Returns 2

UNION

Definition  Return the result of joining two lists. 
Example {{ [4, 5, 6] | union([5, 6, 7]) | join(', ') }}
Returns 4,5,6,7

INTERSECT

Definition  Return to the point where two lists intersect.
Example {{ [4, 5, 6] | intersect([5, 6, 7]) | join(', ') }}
Returns 5,6

DIFFERENCE

Definition  The difference between the two lists returned.
Example {{ [4, 5, 6] | difference([5, 6, 7]) | join(', ') }}
Returns 4

SYMMETRIC_DIFFERENCE

Definition  Give the two lists' symmetrical differences.
Example {{ [4, 5, 6] | symmetric_difference([5, 6, 7]) | join(', ') }}
Returns 4,7

IS_SORTED

Definition  If an iterable item has already been sorted, return True. 
Example {{ [1, 2, 3] | is_sorted }}
Returns True

COMPARE_LISTS 

Definition  A dictionary with the differences is returned after comparing two lists.  
Example {{ [1, 2, 5] | compare_lists([1, 2, 6]) }}
Returns {"new": [6], "old": [5]}

COMPARE_DICTS 

Definition  Return a dictionary with the changes after comparing two dictionaries. 
Example {{ {'a': 'b'} | compare_dicts({'a': 'c'}) }
Returns {"a": {"new": "c", "old": "b"}}

IS_HEX 

Definition  If the value is hexadecimal, return True. 
Example

1. {{ '0xabcd' | is_hex }}

2. {{ 'xyzt' | is_hex }}

Returns

1. True

2. False

CONTAINS_WHITESPACES 

Definition  If a text has whitespace, return True. 
Example

1. {{ 'abcd' | contains_whitespace }}

2. {{ 'ab cd' | contains_whitespace }}

Returns

1. False

2. True

SUBSTRING_IN_LIST 

Definition  Return True if a substring is located in a list of string values. 
Example {{ 'abcd' | substring_in_list(['this', 'is', 'an abcd example']) }}
Returns TRUE

DATE_FORMAT 

Definition  It puts a Unix timestamp into a string that humans can read.
Example

1. {{ 1457456400 | date_format }}

2. {{ 1457456400 | date_format('%d.%m.%Y %H:%M') }}

Returns

1. 2022-12-07

2. 07.12.2022 17:00

TO_NUM

Definition  Gives a string's numerical value in the conversion. 
Example {{ '5' | to_num }}
Returns 5

TO_BYTES

Definition  string-type object to bytes conversion 
Example {{ 'wall of text' | to_bytes }}
Returns 5

JSON_ENCODE_LIST 

Definition 

It json decode list was changed to json encode list. Bytes are produced when something is encoded, and your locale's encoding is produced when something is decoded. When it was initially added, this filter had an incorrect name. Up until the 3003 release, json decode list will be supported.

The to json filter completes the task for which it was intended, making this filter unnecessary.

All string elements in the list are recursively encoded to bytes. 

Example {{ [1, 2, 3] | json_encode_list }} 
Returns [1, 2, 3]

JSON_ENCODE_DICT 

Definition 

The json decode dict was renamed to json encode dict. Bytes are produced when something is encoded, and your locale's encoding is produced when something is decoded (usually a unicode type). When it was initially added, this filter had an inaccurate name. Up until the 3003 release, json decode dict will be supported.

The to json filter completes the task for which it was intended, making this filter unnecessary.

Encodes each string entry in the dictionary one by one into bytes.

Example

Assuming your locale is en-US and pillar['foo'] includes 'u'a': 'u0414'. UTF-8: 

{{ pillar['foo'] | json_encode_dict }}

Returns {"a": "\xd0\x94"}

RANDOM_HASH

Definition 

Changed the filter's name from rand str to random hash to better reflect what it performs. To guarantee backward compatibility, str will be available; however, the random hash is recommended.

 

A random number between 1 and the value supplied to the filter is generated and then hashed. The hash type config option for the minion serves as the default hash type; however, a different hash type can be supplied as an argument to the filter.

Example

{% set num_range = 99999999 %}

{{ num_range | random_hash }}

{{ num_range | random_hash('sha512') }}

Returns

43ec517d68b6edd3015b3edc9a11367b

d94a45acd81f8e3107d237dbc0d5d195f6a52a0d188bc0284c0763ece1eac9f9496fb6a531a296074c87b3540398dace1222b42e150e67c9301383fde3d66ae5

RANDOM_SAMPLE

Definition  It returns from a list of the specified sample size. Returning a predictable result can be achieved by using the seed parameter.
Example

{% set my_list = ["one", "two", "three", "four"] %}

{{ my_list | random_sample(2) }}

Returns ["four", "one"]

RANDOM_SHUFFLE 

Definition  A shuffled copy of the input list is returned. Returning a predictable result can be achieved by using the seed parameter.
Example

{% set my_list = ["one", "two", "three", "four"] %}

{{ my_list | random_shuffle }}

Returns ["four", "three", "one", "two"] 

SET_DICT_KEY_VALUE 

Definition  Gives you the freedom to set a value in a nested dictionary without worrying about whether all the nested keys are present. If no keys are present, they will be generated automatically. The delimiter for the keys is ':' by default, but a different delimiter can be specified using the delimiter parameter. 

Example 1

Example 2

{%- set foo1 = {} %} {{ foo1 | set_dict_key_value('bar1:baz1', 42) }}

{{ {} | set_dict_key_value('bar1.baz1.qux', 42, delimiter='.') }}

Returns 1

Returns 2 

{'bar1': {'baz1': 42}}

{'bar1': {'baz1': {'qux': 42}}}

MD5

Definition  Give the string's md5 digest back. 
Example {{ 'random' | md5 }}
Returns 7ddf32e17a6ac5ce04a8ecbf782ca509

SHA256

Definition  Give the string's sha256 digest back. 
Example {{ 'random' | sha256 }}
Returns 7ddf32e17a6ac5ce04a8ecbf782ca509

SHA512 

Definition  Give the string's sha512 digest back.
Example {{ 'random' | sha512 }}
Returns 811a90e1c8e86c7b4c0eef5b2c0bf0ec1b19c4b1b5a242e6455be93787cb473cb7bc9b0fdeb960d00d5c6881c2094dd63c5c900ce9057255e2a4e271fc25fef1

BASE64_ENCODE

Definition  Base64 encodes a string. 
Example {{ 'random' | base64 }}
Returns 811a90e1c8e86c7b4c0eef5b2c0bf0ec1b19c4b1b5a242e6455be93787cb473cb7bc9b0fdeb960d00d5c6881c2094dd63c5c900ce9057255e2a4e271fc25fef1

HMAC 

Definition  Check a difficult hmac signature against a shared secret or string. Gives a boolean result.
Example {{ 'get salted' | hmac('shared secret', 'eBWf9bstXg+NiP5AOwppB5HMvZiYMPzEM9W5YMm/AmQ=') }}
Returns True

Http_Query 

Definition  From a URL, retrieve the HTTP reply object.
Example {{ 'http://jsonplaceholder.typicode.com/posts/1' | http_query }}
Returns

{

  'body': '{

    "userId": 1,

    "id": 1,

    "title": "Welcome to coding Ninjas!",

    "body": "This blog is about Jinja salt"

  }'

}

TRAVERSE

Definition  From a URL, retrieve the HTTP reply object.
Example {{ {'a1': {'b1': {'c1': 'foo'}}, 'a2': 'bar'} | traverse('a1:b1', 'default') }}
Returns {"c1": "foo"} 

Json_Query

Definition  JSON query, an Ansible port JMESPath language searches against JSON data using the Jinja filter. It might be combined with the http query to filter pillar data, yaml maps, and other data. Depends on the Python function jmespath.
Example {{ [1, 2, 3, 4, [7, 8]] | json_query('[]') }}
Returns [1, 2, 3, 4, 7, 8]

TO_SNAKE_CASE

Definition  A string's camelCase (or CamelCase) case is changed to a snake case. 
Example {{ camelsWillLoveThis | to_snake_case }}
Returns [1, 2, 3, 4, 5, 6]

TO_CAMELCASE

Definition  A string case is changed from a snake case to a camel case.
Example {{ snake_case_for_the_win | to_camelcase }}
Returns snakeCaseForTheWin

HUMAN_TO_BYTES

Definition  Return the number of bytes given a human-readable byte string (for example, 2G, 30MB, or 64KiB). If the argument has an unexpected form, it will return 0. 
Example {{ "32GB" | human_to_bytes }}
Returns 34359738368

STRFTIME 

Any time-related object is transformed into a time-based string. It needs strftime directives that are valid. The Python documentation contains a comprehensive list that can be found here.

{% set curtime = None | strftime() %}


Installing the timelib Python module is necessary to use fuzzy dates.

{{ "2012/11/10"|strftime("%y") }}
{{ "1040814202"|strftime("%Y-%m-%d") }}
{{ datetime|strftime("%u") }}
{{ "tomorrow"|strftime }}

SEQUENCE

A sequence of the parsed data must exist.

YAML_ENCODE 

This serializes a single object into a YAML scalar with any special character handling that may be required. Any scalar YAML data type, including ints, floats, timestamps, booleans, strings, and unicode, will function with this. Sequences and maps that include many items will not function properly.

{%- set bar1 = 5 %}
{%- set baz1 = none %}
{%- set zip1 = false %}
{%- set zap1 = 'The term of the day is "ninjas"' %}
{%- load_yaml as foo %}

bar1: {{ bar1|yaml_encode }}
baz1: {{ baz1|yaml_encode }}
zip1: {{ zip1|yaml_encode }}
zap1: {{ zap1|yaml_encode }}
{%- endload %}


In the above case {{ bar1 }} and {{ foo.bar1 }} should be identical and {{ baz1 }} and {{ foo.baz1 }} should be identical.

YAML_DQUOTE

Converts a string to a double-quoted, appropriately escaped form for YAML. This is helpful when a string's contents are unknown and must be kept because they might contain quotes or unicode. Double quotes will be used for both the beginning and closing of the output string.

{%- set bar = '"The quick brown . . ."' %}
{%- set baz = 'The word of the day "salty".' %}
{%- load_yaml as foo %}
bar: {{ bar|yaml_dquote }}
baz: {{ baz|yaml_dquote }}
{%- endload %}


In the example above, {{ bar }} and {{ foo.bar }} should be similar, and {{ baz }} and {{ foo.baz }} should also be identical. It is preferable to use yaml encode, which supports all YAML scalar types if the contents of a variable are not guaranteed to be a string.

YAML_SQUOTE

Single quotes instead of double quotes, akin to the yaml_dquote filter. Noting that YAML only permits special escapes inside double quotes renders yaml_squote useless; instead, you're probably better off using yaml_encode or yaml_dquote. 

DICT_TO_SLS_YAML_PARAMS

It produces a multiline, formatted YAML string from a Python dictionary. The dictionary's key/value pairs will be appended as single-key dictionaries to a list before being given to the YAML formatter.

Example: 

{% set something_params = {
    "name": "something,"
    "changes": True,
    "warnings": "OMG! Stuff is happening!"
   }
%}

something:
  test.configurable_test_state:
    {{ something_params | dict_to_sls_yaml_params | indent }}


Returns: 

something:
  test.configurable_test_state:
    - name: something
    - changes: true
    - warnings: OMG! Stuff is happening!

TO_BOOL

It returns an element's logical value.

Example: 

{{ 'yes' | to_bool }}
{{ 'true' | to_bool }}
{{ 1 | to_bool }}
{{ 'no' | to_bool }}


Will be Rendered as: 

True
True
True
False

FLATTEN

Flatten a list.

{{ [3, [4, 2] ] | flatten }}
# => [3, 4, 2]


Only flatten the top level of a list:

{{ [3, [4, [2]] ] | flatten(levels=1) }}
# => [3, 4, [2]]


Keep nulls in a list; the flatten command removes them by default.

{{ [3, None, [4, [2]] ] | flatten(levels=1, preserve_nulls=True) }}
# => [3, None, 4, [2]]

COMBINATIONS 

It Activates the itertools library's combinations function. 

{% for one, two in "ABCD" | combinations(2) %}{{ one~two }} {% endfor %}
# => AB AC AD BC BD CD

COMBINATIONS_WITH_REPLACEMENT

It uses the itertools library's combinations with replacement function.

{% for one, two in "ABC" | combinations_with_replacement(2) %}{{ one~two }} {% endfor %}
# => AA AB AC BB BC CC

COMPRESS

It uses the itertools library's compress function as its argument.

{% for val in "ABCDEF" | compress([1,0,1,0,1,1]) %}{{ val }} {% endfor %}
# => A C E F

PERMUTATIONS 

It activates the itertools library's permutations function.

{% for one, two in "ABCD" | permutations(2) %}{{ one~two }} {% endfor %}
# => AB AC AD BA BC BD CA CB CD DA DB DC

Also read, Permutation of string

PRODUCT 

It uses the itertools library's product function, which is invoked.

{% for one, two in "ABCD" | product("xy") %}{{ one~two }} {% endfor %}
# => Ax Ay Bx By Cx Cy Dx Dy

ZIP 

It uses Python's built-in zip function.

It gives a zip object in return; zip operator is an iterator of tuples where the first item and second item in every passed iterator are paired together, and so on.

The iterator with the fewest elements determines the length of the new iterator if the lengths of the previous iterators differed.

{% for one, two in "ABCD" | zip("xy") %}{{ one~two }} {% endfor %}
# => Ax By

ZIP_LONGEST 

invokes the itertools library's zip longest function. 

{% for one, two in "ABCD" | zip_longest("xy", fillvalue="-") %}{{ one~two }} {% endfor %}
# => Ax By C- D-

METHOD_CALL 

It returns the outcome of a method call on the object.

Example 1: 

{{ [1, 2, 1, 3, 4] | method_call('index', 1, 1, 3) }}


Returns:

2 


When used with the map filter, this filter can be used to apply object methods without temporary variables or loop constructions.

Example 2: 

{% set host_list = ['web01.example.com', 'db01.example.com'] %}
{% set host_list_split = [] %}
{% for item in host_list %}
  {% do host_list_split.append(item.split('.', 1)) %}
{% endfor %}
{{ host_list_split }}


Example 3: 

{{ host_list|map('method_call', 'split', '.', 1)|list }}


Return of examples #2 and #3: 

[[web01, example.com], [db01, example.com]]

CHECK_WHITELIST_BLACKLIST

An individual whitelist or blacklist can be used with this filter, or both a whitelist and a blacklist can be passed at once. Value membership is only tested against the whitelist when the whitelist is utilized exclusively. The function returns True if the specified value was located. Otherwise, False is returned.

Value membership is only checked against the blacklist when the blacklist is utilized exclusively. The function returns False when the value is discovered. If not, True is returned.

If a blacklist and a whitelist are offered, the blacklist's value membership will be looked at first. The whitelist is checked if the value is not included in the blacklist. The function returns False if the value cannot be found in the whitelist.

Whitelist Example: 

{{ 6 | check_whitelist_blacklist(whitelist=[5, 6, 7]) }}


Returns:

True 


BlackList Example: 

{{ 6 | check_whitelist_blacklist(blacklist=[5, 6, 7]) }}


Returns:

False

TOJSON 

A data structure is dumped to JSON.

This filter was added to give hosts running Jinja releases older than version 2.9 access to this functionality. The upstream version of the filter will be used if Jinja version 2.9 or higher is installed. For further details, consult the upstream documentation.

Networking Filters 

Supported networking-related filters include: 

IS_IP 

If a string contains an IP address, return true. 

{{ '192.168.0.1' | is_ip }}

Accepts the following choices as well:

  • Global
     
  • Link-local
     
  • Loopback
     
  • Multicast
     
  • Private
     
  • Public
     
  • Reserved
     
  • Site-local
     
  • Unspecified
     

For instance, test a string to see if it is a legitimate loopback IP address.

{{ '192.168.0.1' | is_ip(options='loopback') }}

IS_IPV4

Indicates whether a string is a valid IPv4 address. Has the same choices that ip does.

{{ '192.168.0.1' | is_ipv4 }}

IS_IPV6

Determines whether a string is an IPv6 address. Has the same choices that ip does.

{{ 'fe80::' | is_ipv6 }}

IPADDR

Definition  Only displays valid IP entries from a list. Has the same choices that ip does. IP networks and interfaces may also be included in the list.
Example {{ ['192.168.0.1', 'foo', 'bar', 'fe80::'] | ipaddr }}
Returns ["192.168.0.1", "fe80::"]

IPV4 

Definition  It only displays valid IPv4 entries from a list. Has the same choices that ip does. IP networks and interfaces may also be included in the list.
Example {{ ['192.168.0.1', 'foo', 'bar', 'fe80::'] | ipv4 }}
Returns ["192.168.0.1"]

IPV6 

Definition  It only displays valid IPv6 entries from a list. Has the same choices that ip does. IP networks and interfaces may also be included in the list.
Example {{ ['192.168.0.1', 'foo', 'bar', 'fe80::'] | ipv6 }}
Returns ["fe80::"]

Network_Hosts 

Definition  Give back a list of hosts in a network. This utility supports both IPv4 and IPv6.  
Example {{ '192.168.0.1/30' | network_hosts }}
Returns ["192.168.0.1", "192.168.0.2"]

Network_Size 

Definition  Give the network's size back. This utility supports both IPv4 and IPv6.  
Example {{ '192.168.0.1/8' | network_size }}
Returns 16777216

Gen_Mac 

Definition 

A MAC address is generated with the specified OUI prefix.

Common prefixes:

  • 00:16:3E -- Xen
  • 00:18:51 -- OpenVZ
  • 00:50:56 -- VMware (manually generated)
  • 52:54:00 -- QEMU/KVM
  • AC:DE:48 -- PRIVATE
Example {{ '00:50' | gen_mac }}
Returns 00:50:71:52:1C

MAC_TO_STR_BYTES

Definition  Translates a valid MAC address represented by a text into bytes.
Example {{ '192.168.0.1/30' | network_hosts }}

DNS_CHECK

Definition  Return the IP that DNS could resolve, but do not abort; instead, throw an exception. Respects the system's preferred method of resolving IPv4/IPv6 addresses.
Example {{ 'www.google.com' | dns_check(port=443) }}
Returns '172.217.3.196'

File Filters 

IS_TEXT_FILE 

Definition 

If a file is a text, return it.

Simply reading a single block of bytes from the file uses heuristics to determine whether the supplied file is text or binary. Assume this is a binary file if the block contains NUL ('x00') bytes, or more than 30% of the characters are not text.

Example {{ '/etc/salt/master' | is_text_file }}
Returns True

IS_BINARY_FILE 

Definition 

If a file is binary, return true.

Determines whether the file is binary and returns a bool. If the file is a bin, the return value is True; otherwise, it is False; and if the file is unavailable, it is None.

Example {{ '/etc/salt/master' | is_binary_file }}
Returns False

IS_EMPTY_FILE 

Definition  If a file is empty, return it. 
Example {{ '/etc/salt/master' | is_empty_file }}
Returns False

FILE_HASHSUM  

Definition  Get a file's hash sum back.
Example {{ '/etc/salt/master' | file_hashsum }}
Returns 02d4ef135514934759634f10079653252c7ad594ea97bd385480c532bca0fdda

List_Files  

Definition  Return a list of files under a specific directory in recursive mode.  
Example {{ '/etc/salt/' | list_files | join('\n') }
Returns

/etc/salt/master

/etc/salt/proxy

/etc/salt/minion

/etc/salt/pillar/top.sls

/etc/salt/pillar/device1.sls

Path_Join 

Definition  Connects exact pathways. 
Example {{ '/etc/salt/' | path_join('pillar', 'device1.sls') }}
Returns /etc/salt/pillar/device1.sls

WHICH 

Definition  Python clone of /usr/bin/which.  
Example {{ 'salt-master' | which }}
Returns /usr/local/salt/virtualenv/bin/salt-master

Tests 

Saltstack adds these unique tests to the built-in tests. 

EQUAL TO

Checks whether two values are equal.

Direct use in an if statement is possible:

{% if 1 is equalto(1) %}
    < statements >
{% endif %}


If the condition is evaluated as True

the selectattr filter, or

{{ [{'value': 1}, {'value': 2} , {'value': 3}] | selectattr('value', 'equalto', 3) | list }}


Returns: 

[{"value": 3}]

MATCH 

It checks whether a string matches the regex passed as an argument.

Direct use in an if statement is possible:

{% if 'a' is match('[a-b]') %}
    < statements >
{% endif %}


If clause evaluates to True

or with the selectattr filter:

{{ [{'value': 'a'}, {'value': 'b'}, {'value': 'c'}] | selectattr('value', 'match', '[b-e]') | list }}


Returns: 

[{"value": "b"}, {"value": "c"}]


Additional possible inputs for the test include ignore-case and multiline. 

Escape Filters 

Regex_Escape 

It allows for the escape of strings so that another function can interpret them literally.

Example: 

regex_escape = {{ 'https://example.com?coding=ninjas%20baz' | regex_escape }}


Will be rendered as:

regex_escape = https\:\/\/example\.com\?coding\=ninjas\%20baz

Frequently Asked Questions

What is saltstack?

Salt is a configuration management and remote execution tool that helps execute commands on the remote node. It is simple to use, fast and can be easily manageable. 

Where do we use saltstack?

The saltstack is an orchestration tool that helps change existing systems. It helps easily install the software in the IT environment and helps manage thousands of servers in a single go. 

Is saltstack still free of cost to developers?

Saltstack is a free, open-source download and is free of cost to the programmers; however, their enterprise version costs $150 per machine per year. 

What is SaltStack's drawback? 

SaltStack lacks a user interface with many features. As a result, users use the command-line tool appropriately to complete their duties.

What is the advantage of saltstack? 

With one minion that can command others, SaltStack can be set up in a tiered configuration to achieve load balancing and boast redundancy. 

Conclusion

In this article, we discussed the introduction to Jinja in salt, along with the the states of Jinja, and all the filters in Jinja in salt. 

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in our courses and refer to the mock test and problems available; look at the Top 150 Interview Puzzles interview experiences, and interview bundle for placement preparations. Read our blogs on aptitudecompetitive programminginterview questionsIT certifications, and data structures and algorithms for the best practice.

Live masterclass