Do you think IIT Guwahati certified course can help you in your career?
No
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.
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:
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:
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.