Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Mastering SaltStack
Mastering SaltStack

Mastering SaltStack: Use Salt to the fullest , Second Edition

eBook
€22.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Table of content icon View table of contents Preview book icon Preview Book

Mastering SaltStack

Chapter 1.  Essentials Revisited

Salt is a very powerful remote automation framework. Before we delve into the more advanced topics that this book covers, it would be wise to go back and review a few essentials. In this chapter, we will cover the following topics:

  • Using remote execution
  • Basic SLS file tree structure
  • Using states for configuration management
  • Basics of grains, pillars, and templates

This book assumes that you already have root access on a device with a common distribution of Linux installed. The machine used in the examples in this book is running Ubuntu 14.04, unless stated otherwise. Most examples should run on other major distributions, such as recent versions of Fedora, RHEL 5/6/7, Suse, or Arch Linux.

Executing commands remotely

The underlying architecture of Salt is based on the idea of executing commands remotely. This is not a new concept; all networking is designed around some aspect of remote execution. This could be as simple as asking a remote web server to display a static Web page, or as complex as using a shell session to interactively issue commands against a remote server.

Under the hood, Salt is a more complex example of remote execution. But whereas most Internet users are used to interacting with only one server at a time (so far as they are aware), Salt is designed to allow users to explicitly target and issue commands to multiple machines directly.

Master and minions

Salt is based around the idea of a master, which controls one or more minions. Commands are normally issued from the master to a target group of minions, which then execute the tasks specified in the commands and return any resulting data back to the master.

Targeting minions

The first facet of the salt command is targeting. A target must be specified with each execution, which matches one or more minions. By default, the type of target is a glob, which is the style of pattern matching used by many command shells. Other types of targeting are also available, by adding a flag. For instance, to target a group of machines inside a particular subnet, the -S option is used:

# salt -S 192.168.0.0/24 test.ping

The following are most of the available target types, along with some basic usage examples. Not all target types are covered here; Range, for example, extends beyond the scope of this book. However, the most common types are covered.

Glob

This is the default target type for Salt, so it does not have a command line option. The minion ID of one or more minions can be specified, using shell wildcards if desired.

When the salt command is issued from most command shells, wildcard characters must be protected from shell expansion:

# salt '*' test.ping
# salt \* test.ping

When using Salt from an API or from other user interfaces, quoting and escaping wildcard characters is generally not required.

Perl Compatible Regular Expression (PCRE)

Short Option: -E

Long Option: --pcre

When more complex pattern matching is required, a Perl Compatible Regular Expression (PCRE) can be used. This type of targeting was added to the earliest versions of Salt, and was meant largely to be used inside shell scripts. However, its power can still be realized from the command line:

# salt -E '^[m|M]in.[e|o|u]n$' test.ping

List

Short Option: -L

Long Option: --list

This option allows multiple minions to be specified as a comma-separated list. The items in this list do not use pattern matching such as globbing or regular expressions; they must be declared explicitly:

# salt -L web1,web2,db1,proxy1 test.ping

Subnet

Short Option: -S

Long Option: --ipcidr

Minions may be targeted based on a specific IPv4 or an IPv4 subnet in CIDR notation:

# salt -S 192.168.0.42 test.ping
# salt -S 192.168.0.0/16 test.ping

As of Salt version 2016.3, IPv6 addresses cannot be targeted by a specific command line option. However, there are other ways to target IPv6 addresses. One way is to use grain matching.

Grain

Short Version: -G

Long Version: --grain

Salt can target minions based on individual pieces of information that describe the machine. This can range from the OS to CPU architecture to custom information (covered in more detail later in this chapter). Because some network information is also available as grains, IP addresses can also be targeted this way.

Since grains are specified as key/value pairs, both the name of the key and the value must be specified. These are separated by a colon:

# salt -G 'os:Ubuntu' test.ping
# salt -G 'os_family:Debian' test.ping

Some grains are returned in a multi-level dictionary. These can be accessed by separating each key of the dictionary with a colon:

# salt -G 'ip_interfaces:eth0:192.168.11.38'

Grains which contain colons may also be specified, though it may look strange. The following will match the local IPv6 address (::1). Note the number of colons used:

# salt -G 'ipv6:::1' test.ping

Grain PCRE

Short Version: (not available)

Long Version: --grain-pcre

Matching by grains can be powerful, but the ability to match by a more complex pattern is even more so.

# salt --grain-pcre 'os:red(hat|flag)' test.ping

Pillar

Short Option: -I

Long Option: --pillar

It is also possible to match based on pillar data. Pillars are described in more detail later in the chapter, but for now we can just think of them as variables that look like grains.

# salt -I 'my_var:my_val' test.ping

Compound

Short Option: -C

Long Option: --compound

Compound targets allow the user to specify multiple target types in a single command. By default, globs are used, but other target types may be specified by preceding the target with the corresponding letter followed by the @ sign:

Letter

Target

G

Grains

E

PCRE minion ID

P

PCRE grains

L

List

I

Pillar

J

Pillar PCRE

S

Subnet/IP address

R

SECO range

The following command will target the minions that are running Ubuntu, have the role pillar set to web, and are in the 192.168.100.0/24 subnet.

# salt -C 'G@os:Ubuntu and I@role:web and S@192.168.100.0/24' test.ping

Boolean grammar may also be used to join target types, including and, or, and not operators.

# salt -C 'min* or *ion' test.ping
# salt -C 'web* or *qa and G@os:Arch' test.ping

Nodegroup

Short Option: -N

Long Option: --nodegroup

While nodegroups are used internally in Salt (all targeting ultimately results in the creation of an on-the-fly nodegroup), it is much less common to explicitly use them from the command line. Node groups must be defined as a list of targets (using compound syntax) in the Salt master's configuration before they can be used from the command line. Such a configuration might look like the following:

nodegroups: 
  webdev: 'I@role:web and G@cluster:dev'  webqa: 'I@role:web and
  G@cluster:qa'  webprod: 'I@role:web and G@cluster:prod'

Once a nodegroup is defined and the master configuration reloaded, it can be targeted from Salt:

# salt -N webdev test.ping

Using module functions

After a target is specified, a function must be declared. The preceding examples all use the test.ping function but, obviously, other functions are available. Functions are actually defined in two parts, separated by a period:

<module> . <function> 

Inside a Salt command, these follow the target, but precede any arguments that might be added for the function:

salt <target> <module>.<function> [arguments...] 

For instance, the following Salt command will ask all minions to return the text, "Hello world":

salt '*' test.echo 'Hello world'

A number of execution modules ship with the core Salt distribution, and it is possible to add more. Version 2016.3 of Salt ships with around 400 execution modules. Not all modules are available for every platform; in fact, by design, some modules will only be available to the user if they are able to detect the required underlying functionality.

For instance, all functions in the test module are necessarily available on all platforms. These functions are designed to test the basic functionality of Salt and the availability of minions. Functions in the Apache module, however, are only available if the necessary commands are located on the minion in question.

Execution modules are the basic building blocks of Salt; other modules in Salt use them for their heavy lifting. Because execution modules are generally designed to be used from the command line, an argument for a function can usually be passed as a string. However, some arguments are designed to be used from other parts of Salt. To use these arguments from the command line, a Python-like data structure is emulated using a JSON string.

This makes sense, since Salt is traditionally configured using YAML, and all JSON is syntactically-correct YAML. Be sure to surround the JSON with single quotes on the command line to avoid shell expansion, and use double quotes inside the string. The following examples will help.

A list is declared using brackets:

'["item1","item2","item3"]' 

A dictionary is declared using braces (that is, curly brackets):

'{"key1":"value1","key2":"value2","key3":"value3"}' 

A list can include a dictionary, and a dictionary can include a list:

'[{"key1":"value1"},{"key2":"value2"}]' 
'{"list1":["item1","item2"],"list2":["item3","item4"]}' 

There are a few modules which can be considered core to Salt, and a handful of functions in each that are widely used.

test.ping

This is the most basic Salt command. Ultimately, it only asks the minion to return True. This function is widely used in documentation because of its simplicity, and to check whether a minion is responding. Don't worry if a minion doesn't respond right away; that doesn't necessarily mean it's down. A number of variables could cause a slower-than-usual return. However, successive failed attempts may be cause for concern.

test.echo

This function does little more than the test.ping command; it merely asks the minion to echo back a string that is passed to it. A number of other functions exist that perform similar tasks, including test.arg, test.kwarg, test.arg_type, and test.arg_repr.

test.sleep

A slightly more advanced testing scenario may require a minion to sleep for a number of seconds before returning True. This is often used to test or demonstrate the utilities that make use of the jobs system. The test.rand_sleep function is also useful for test cases where it is desirable to check the return from a large number of minions, with the return process spread out.

test.version

In a large enough infrastructure, a number of minions are bound to be running in a different version of Salt than others. When troubleshooting issues specific to certain versions of Salt, it helps to be able to take a quick look at the Salt version on each minion. This is the simplest way to check that. Checking the version of other packages that are maintained by the system packaging system can be performed with pkg.version.

pkg.install

Every package manager in Salt (as of version 2016.3) supports installing a package. This function can be as simple as asking for a single package name, or as complex as passing through a list of packages, each with a specific version. When using an execution module, you generally do not need to specify more than just a single package name, but inside the state module (covered later) the advanced functionality becomes more important.

pkg.remove

This matches the pkg.install function, allowing a certain package to be removed. Because versions are not so important when removing packages, this function doesn't get so complex. But it does allow passing a list of packages to be removed (using the pkgs argument) as a Python list. From the command line, this can be done using a JSON string.

file.replace

The sed command is one of the oldest members of the Unix administrator's toolkit. It has been the go-to command largely for tasks that involve editing files inline, and performing search and replace tasks. There have been a few attempts over the years to duplicate the functionality of the sed command. Initially, the file.sed function simply wrapped the Unix sed command. The file.psed function provided a Python-based replacement. However, sed is more than just a find/replace tool; it is a full language that can be problematic when used incorrectly. The file.replace function was designed from the ground up to provide the find/replace functionality that most users need, while avoiding the subtle nuances that can be caused by wrapping sed.

Other file functions

A number of common Unix commands have been added to the file function. The following functions complement the Unix command set for managing files and their metadata: file.chown, file.chgrp, file.get_mode, file.set_mode, file.link, file.symlink, file.rename, file.copy, file.move, file.remove, file.mkdir, file.makedirs, file.mknod, and a number of others.

Various user and group functions

The Unix toolset for managing users and groups is also available in Salt and includes user.add, user.delete, user.info, group.add, group.delete, group.info, user.chuid, user.chgid, user.chshell, user.chhome, user.chgroups, and many, many more.

sys.doc

By design, every public function in every execution module must be self-documenting. The documentation that appears at the top of the function should contain a description just long enough to describe the general use of the function, and must include at least one CLI example demonstrating the usage of that function.

This documentation is available from the minion using the sys.doc function. Without any arguments, it will display all the functions available on a particular minion. Adding the name of a module will show only the available functions in that module, and adding the name of a function will show only the documentation for that function, if it is available. This is an extremely valuable tool, both for providing simple reminders of how to use a function and for discovering which modules are available.

SLS file trees

There are a few subsystems in Salt that use an SLS file tree. The most common one of course is /srv/salt/, which is used for Salt states. Right after states are pillars (/srv/pillar/), which use a different file format but the same directory structure. Let's take a moment to talk about how these directories are put together.

SLS files

SLS stands for Salt State, which was the first type of file inside Salt to use this kind of file structure. While SLS files can be rendered in a number of different formats, by far the widest use is the default, YAML. Various templating engines are also available to help form the YAML (or other data structure) and again, the most popular is the default, Jinja.

Keep in mind that Salt is all about data. YAML is a serialization format that in Python, represents a data structure in a dictionary format. When thinking about how SLS files are designed, remember that they are a key/value pair: each item has a unique key, which is used to refer to a value. The value can in turn contain a single item, a list of items, or another set of key/value pairs.

The key to a stanza in an SLS file is called an ID. If no name inside the stanza is explicitly declared, the ID is copied to the name. Remember that IDs must be globally unique; duplicate IDs will cause errors.

Tying things together with top files

Both the state and the pillar system use a file called top.sls to pull the SLS files together and serve them to the appropriate minions, in the appropriate environments.

Each key in a top.sls file defines an environment. Typically, a base environment is defined, which includes all the minions in the infrastructure. Then other environments are defined that contain only a subset of the minions. Each environment includes a list of the SLS files that are to be included. Take the following top.sls file:

base: 
  '*': 
    - common 
    - vim 
qa: 
  '*_qa': 
    - jenkins 
web: 
  'web_*': 
    - apache2 

With this top.sls, three environments have been declared: base, qa, and web. The base environment will execute the common and vim states across all minions. The qa environment will execute the jenkins state across all the minions whose ID ends with _qa. The web environment will execute the apache2 state across all the minions whose ID starts with web_.

Organizing the SLS directories

SLS files may be named either as an SLS file themselves (that is, apache2.sls) or as an init.sls file inside a directory with the SLS name (that is, apache2/init.sls).

Note

Note that apache2.sls will be searched for first; if it is not there, then apache2/init.sls will be used.

SLS files may be hierarchical, and there is no imposed limit on how deep directories may go. When defining deeper directory structures, each level is appended to the SLS name with a period (that is, apache2/ssl/init.sls becomes apache2.ssl). It is considered best practice by developers to keep a directory more shallow; don't make your users search through your SLS tree to find things.

Using states for configuration management

The files inside the /srv/salt/ directory define the Salt states. This is a configuration management format that enforces the state that a minion will be in: package X needs to be installed, file Y needs to look a certain way, service Z needs to be enabled and running, and so on. For example:

apache2: 
  pkg: 
    - installed 
  service: 
    - running 
  file: 
    - name: /etc/apache2/apache2.conf 

States may be saved in a single SLS file, but it is far better to separate them into multiple files, in a way that makes sense to you and your organization. SLS files can use include blocks that pull in other SLS files.

Using include blocks

In a large SLS tree, it often becomes reasonable to have SLS files include other SLS files. This is done using an include block, which usually appears at the top of an SLS file:

include: 
  - base 
  - emacs 

In this example, the SLS file in question will replace the include block with the contents of base.sls (or base/init.sls) and emacs.sls (or emacs/init.sls). This imposes some important restrictions on the user. Most importantly, the SLS files that are included may not contain IDs that already exist in the SLS file that includes them.

It is also important to remember that include itself, being a top-level declaration, cannot exist twice in the same file. The following is invalid:

include: 
  - base 
include: 
  - emacs 

Ordering with requisites

State SLS files are unique among configuration management formats in that they are both declarative and imperative. They are imperative, as each state will be evaluated in the order in which it appears in the SLS file. They are also declarative because states may include requisites that change the order in which they are actually executed. For instance:

web_service: 
  service.running: 
    - name: apache2 
    - require: 
      - pkg: web_package 
web_package: 
  pkg.installed: 
    - name: apache2 

If a service is declared, which requires a package that appears after it in the SLS file, the pkg states will be executed first. However, if no requirements are declared, Salt will attempt to start the service before installing the package, because its codeblock appears before the pkg codeblock. The following will require two executions to complete properly:

web_service: 
  service.running: 
    - name: apache2 
web_package: 
  pkg.installed: 
    - name: apache2 

Requisites point to a list of items elsewhere in the SLS file that affect the behavior of the state. Each item in the list contains two components: the name of the module and the ID of the state being referenced.

The following requisites are available inside Salt states and other areas of Salt that use the state compiler.

require

The require requisite is the most basic; it dictates that the state that it is declared in is not executed until every item in the list that has been defined for it has executed successfully. Consider the following example:

apache2: 
  pkg: 
    - installed 
    - require 
      - file: apache2 
  service: 
    - running 
    - require: 
      - pkg: apache2 
  file: 
    - managed 
    - name: /etc/apache2/apache2.conf 
    - source: salt://apache2/apache2.conf 

In this example, a file will be copied to the minion first, then a package installed, then the service started. Obviously, the service cannot be started until the package that provides it is installed. But Debian-based operating systems such as Ubuntu automatically start services the moment they're installed, which can be problematic if the default configuration files aren't correct. This state will ensure that Apache is properly configured before it is even installed.

watch

In the preceding example, a new minion will be properly configured the first time. However, if the configuration file changes, the apache2 service will need to be restarted. Adding a watch requisite to the service will force that state to perform a specific action when the state that it is watching reports changes.

apache2: 
  ...SNIP... 
  service: 
    - running 
    - require: 
      - pkg: apache2 
    - watch: 
      - file: apache2 
  ...SNIP... 

The watch requisite is not available for every type of state module. This is because it performs a specific action, depending on the type of module. For instance, when a service is triggered with a watch, Salt will attempt to start a service that is stopped. If it is already running, it will attempt either a reload: True, service.full_restart, or service.restart, as appropriate.

As of version 2016.3, the following states modules support using the watch requisite: service, pkg, cmd, event, module, mount, supervisord, docker, dockerng, etcd, tomcat, and test.

onchanges

The onchanges requisite is similar to watch, except that it does not require any special support from the state module that is using it. If changes happen, which should only occur when a state completes successfully, then the list of items referred to with onchanges will be evaluated.

onfail

In a simple state tree, the onfail requisite is less commonly used. However, a more advanced state tree, which is written to attempt alerting the user, or to perform auto-correcting measures, can make use of onfail. When a state is evaluated and fails to execute correctly, every item listed under onfail will be evaluated. Assuming that the PagerDuty service is properly configured via Salt and an apache_failure state has been written to use it, the following state can notify the operations team if Apache fails to start:

apache2: 
  service: 
    - running 
    - onfail 
      - pagerduty: apache_failure 

use

It is possible to declare default values in one state and then inherit them into another state. This typically occurs when one state file has an include statement that refers to another file.

If an item in the state that is being used has been redeclared, it will be overwritten with the new value. Otherwise, the item that is being used will appear unchanged. Requisites will not be inherited with use; only non-requisite options will be inherited. Therefore, in the following SLS, the mysql_conf state will safely inherit the user, group, and mode from the apache2_conf state, without also triggering Apache restarts:

apache2_conf: 
  file: 
    - managed 
    - name: /etc/apache2/apache2.conf 
    - user: root 
    - group: root 
    - mode: 755 
    - watch_in: 
      - service: apache2 
mysql_conf: 
file: 
  - managed 
    - name: /etc/mysql/my.cnf 
    - use: 
      - file: apache2_conf 
    - watch_in: 
      - service: mysql 

prereq

There are some situations in which a state does not need to run, unless another state is expected to make changes. For example, consider a web application that makes use of Apache. When the codebase on a production server changes, Apache should be turned off, so as to avoid errors with the code that has not yet finished being installed.

The prereq requisite was designed exactly for this kind of use. When a state makes use of prereq, Salt will first perform a test run of the state to see if the items referred to in the prereq are expected to make changes. If so, then Salt will flag the state with the prereq as needing to execute.

apache2: 
  service: 
    - running 
    - watch: 
      - file: codebase 
codebase: 
  file: 
    - recurse 
...SNIP... 
shutdown_apache: 
  service: 
    - dead 
    - name: apache2 
    - prereq: 
      - file: codebase 

In the preceding example, the shutdown_apache state will only make changes if the codebase state reports that changes need to be made. If they do, then Apache will shutdown, and then the codebase state will execute. Once it is finished, it will trigger the apache2 service state, which will start up Apache again.

Inverting requisites

Each of the aforementioned requisites can be used inversely, by adding _in at the end. For instance, rather than state X requiring state Y, an SLS can be written so that state X declares that it is required by state Y, as follows:

apache2: 
  pkg: 
    - installed 
    - require_in: 
      - service: apache2 
  service: 
    - running 

It may seem silly to add inverses of each of the states but there is in fact a very good use case for doing so: include blocks.

SLS files cannot use requisites that point to a code that does not exist inside them. However, using an include block will cause the contents of other SLS files to appear inside the SLS file. Therefore, generic (but valid) configuration can be defined in one SLS file, included in another, and modified to be more specific with a use_in requisite.

Extending SLS files

In addition to an include block, state SLS files can also contain an extend block that modifies SLS files that appear in the include block. Using an extend block is similar to a use requisite, but there are some important differences.

Whereas a use or use_in requisite will copy defaults to or from another state, the extend block will only modify the state that has been extended.

# cat /srv/generic_apache/init.sls 
apache2_conf: 
  file: 
  - managed 
    - name: /etc/apache2/apache2.conf 
    - source: salt://apache2/apache2.conf 
(In django_server/init.sls) 
include: 
- generic_apache 
extend: 
  apache2_conf: 
    file: 
    - source: salt://django/apache2.conf 
(In image_server/init.sls) 
include: 
  - generic_apache 
extend: 
  apache2_conf: 
    file: 
      - source: salt://django/apache2.conf 

The preceding example makes use of a generic Apache configuration file, which will be overridden as appropriate for either a Django server or a web server that is only serving images.

The basics of grains, pillars, and templates

Grains and pillars provide a means of allowing user-defined variables to be used in conjunction with a minion. Templates can take advantage of those variables to create files on a minion that are specific to that minion.

Before we get into details, let me start off by clarifying a couple of things: grains are defined by the minion which they are specific to, while pillars are defined on the master. Either can be defined statically or dynamically (this book will focus on static), but grains are generally used to provide data that is unlikely to change, at least without restarting the minion, while pillars tend to be more dynamic.

Using grains for minion-specific data

Grains were originally designed to describe the static components of a minion, so that execution modules could detect how to behave appropriately. For instance, minions which contain the Debian os_family grain are likely to use the apt suite of tools for package management. Minions which contain the RedHat os_family grain are likely to use yum for package management.

A number of grains will automatically be discovered by Salt. Grains such as os, os_family, saltversion, and pythonversion are likely to be always available. Grains such as shell, systemd, and ps are not likely to be available on, for instance, Windows minions.

Grains are loaded when the minion process starts up, and then cached in memory. This improves minion performance, because the Salt-minion process doesn't need to rescan the system for every operation. This is critical to Salt, because it is designed to execute tasks immediately, and not wait several seconds on each execution.

To discover which grains are set on a minion, use the grains.items function:

salt myminion grains.items

To look at only a specific grain, pass its name as an argument to grains.item:

salt myminion grains.item os_family

Custom grains can be defined as well. Previously, static grains were defined in the minion configuration file (/etc/salt/minion on Linux and some Unix platforms):

grains: 
  foo: bar 
  baz: qux 

However, while this is still possible, it has fallen out of favor. It is now more common to define static grains in a file called grains (/etc/salt/grains on Linux and some Unix platforms). Using this file has some advantages:

  • Grains are stored in a central, easy-to-find location
  • Grains can be modified by the grains execution module

That second point is important: whereas the minion configuration file is designed to accommodate user comments, the grains file is designed to be rewritten by Salt as necessary. Hand-editing the grains file is fine, but don't expect any comments to be preserved. Other than not including the grains top-level declaration, the grains file looks like the grains configuration in the minion file:

foo: bar 
baz: qux 

To add or modify a grain in the grains file, use the grains.setval function:

salt myminion grains.setval mygrain 'This is the content of mygrain'

Grains can contain a number of different types of values. Most grains contain only strings, but lists are also possible:

my_items: 
  - item1 
  - item2 

In order to add an item to this list, use the grains.append function:

salt myminion grains.append my_items item3

In order to remove a grain from the grains file, use the grains.delval function:

salt myminion grains.delval my_items

Centralizing variables with pillars

In most instances, pillars behave in much the same way as grains, with one important difference: they are defined on the master, typically in a centralized location. By default, this is the /srv/pillar/ directory on Linux machines. Because one location contains information for multiple minions, there must be a way to target that information to the minions. Because of this, SLS files are used.

The top.sls file for pillars is identical in configuration and function to the top.sls file for states: first an environment is declared, then a target, then a list of SLS files that will be applied to that target:

base: 
  '*': 
    - bash 

Pillar SLS files are much simpler than state SLS files, because they serve only as a static data store. They define key/value pairs, which may also be hierarchical.

skel_dir: /etc/skel/ 
role: web 
web_content: 
  images: 
    - jpg 
    - png 
    - gif 
  scripts: 
    - css 
    - js 

Like state SLS files, pillar SLS files may also include other pillar SLS files.

include: 
  - users 

To view all pillar data, use the pillar.items function:

salt myminion pillar.items

Take note that in older versions of Salt, when running this command, by default the master's configuration data will appear as a pillar item called master. This can cause problems if the master configuration includes sensitive data. To disable this output, add the following line to the master configuration:

pillar_opts: False 

Fortunately, this option defaults to False as of Salt version 2015.5.0. This is also a good time to mention that, outside the master configuration data, pillars are only viewable to the minion or minions to which they are targeted. In other words, no minion is allowed to access another minion's pillar data, at least by default. It is possible to allow a minion to perform master commands using the peer system, but that is outside the scope of this chapter.

Managing files dynamically with templates

Salt is able to use templates, which take advantage of grains and pillars, to make the state system more dynamic. A number of other templating engines are also available, including (as of version 2016.3) the following:

  • jinja
  • mako
  • wempy
  • cheetah
  • genshi

These are made available via Salt's rendering system. The preceding list only contains renderers that are typically used as templates to create configuration files and the like. Other renderers are available as well, but are designed more to describe data structures:

  • yaml
  • yamlex
  • json
  • json5
  • msgpack
  • py
  • pyobjects
  • pydsl

Finally, the following Renderer can decrypt GPG data stored on the master, before passing it through another renderer:

  • gpg

By default, state SLS files will be sent through the Jinja renderer, and then the yaml renderer. There are two ways to switch an SLS file to another renderer. First, if only one SLS file needs to be rendered differently, the first line of the file can contain a shabang line that specifies the renderer:

#!py 

The shabang can also specify multiple Renderers, separated by pipes, in the order in which they are to be used. This is known as a render pipe. To use Mako and JSON instead of Jinja and YAML, use:

#!mako|json 

To change the system default, set the renderer option in the master configuration file. The default is:

renderer: yaml_jinja 

It is also possible to specify the templating engine to be used on a file that created the minion using the file.managed state:

apache2_conf: 
  file: 
    - managed 
    - name: /etc/apache2/apache2.conf 
    - source: salt://apache2/apache2.conf 
    - template: jinja 

A quick Jinja primer

Because Jinja is by far the most commonly-used templating engine in Salt, we will focus on it here. Jinja is not hard to learn, and a few basics will go a long way.

Variables can be referred to by enclosing them in double-braces. Assuming a grain is set called user, the following will access it:

The user {{ grains['user'] }} is referred to here. 

Pillars can be accessed in the same way:

The user {{ pillar['user'] }} is referred to here. 

However, if the user pillar or grain is not set, the template will not render properly. A safer method is to use the salt built-in to cross-call an execution module:

The user {{ salt['grains.get']('user', 'larry') }} is referred to here. 
The user {{ salt['pillar.get']('user', 'larry') }} is referred to here. 

In both of these examples, if the user has not been set, then larry will be used as the default.

We can also make our templates more dynamic by having them search through grains and pillars for us. Using the config.get function, Salt will first look inside the minion's configuration. If it does not find the requested variable there, it will check the grains. Then it will search pillar. If it can't find it there, it will look inside the master configuration. If all else fails, it will use the default provided.

The user {{ salt['config.get']('user', 'larry') }} is referred to here. 

Codeblocks are enclosed within braces and percent signs. To set a variable that is local to a template (that is, not available via config.get), use the set keyword:

{% set myvar = 'My Value' %} 

Because Jinja is based on Python, most Python data types are available. For instance, lists and dictionaries:

{% set mylist = ['apples', 'oranges', 'bananas'] %} 
{% set mydict = {'favorite pie': 'key lime', 'favorite cake': 'saccher torte'} %} 

Jinja also offers logic that can help define which parts of a template are used, and how. Conditionals are performed using if blocks. Consider the following example:

{% if grains['os_family'] == 'Debian' %} 
apache2: 
{% elif grains['os_family'] == 'RedHat' %} 
httpd: 
{% endif %} 
  pkg: 
    - installed 
  service: 
    - running 

The Apache package is called apache2 on Debian-style systems, and httpd on RedHat-style systems. However, everything else in the state is the same. This template will auto-detect the type of system that it is on, install the appropriate package, and start the appropriate service.

Loops can be performed using for blocks, as follows:

{% set berries = ['blue', 'rasp', 'straw'] %} 
{% for berry in berries %} 
{{ berry }}berry 
{% endfor %} 

Summary

Salt is designed first and foremost for remote execution. Most tasks in Salt are performed as a type of remote execution. One of the most common types of remote execution in Salt is configuration management, using states. Minion-specific data can be declared in grains and pillars, and used in state files and templates.

With a basic foundation of Salt behind us, let's move on to the good stuff. In the next chapter, we will dive into the internals of Salt, and discuss why and how Salt does what it does.

Left arrow icon Right arrow icon

Key benefits

  • Automate tasks effectively and take charge of your infrastructure
  • Effectively scale Salt to manage thousands of machines and tackle everyday problems
  • Explore Salt’s inner workings and advance your knowledge of it

Description

SaltStack is a powerful configuration management and automation suite designed to manage servers and tens of thousands of nodes. This book showcases Salt as a very powerful automation framework. We will review the fundamental concepts to get you in the right frame of mind, and then explore Salt in much greater depth. You will explore Salt SSH as a powerful tool and take Salt Cloud to the next level. Next, you’ll master using Salt services with ease in your infrastructure. You will discover methods and strategies to scale your infrastructure properly. You will also learn how to use Salt as a powerful monitoring tool. By the end of this book, you will have learned troubleshooting tips and best practices to make the entire process of using Salt pain-free and easy.

Who is this book for?

This book is ideal for IT professionals and ops engineers who already manage groups of servers, but would like to expand their knowledge and gain expertise with SaltStack. This book explains the advanced features and concepts of Salt. A basic knowledge of Salt is required in order to get to grips with advanced Salt features.

What you will learn

  • Automate tasks effectively, so that your infrastructure can run itself
  • Start building more complex concepts
  • Master user-level internals
  • Build scaling strategies
  • Explore monitoring strategies
  • Learn how to troubleshoot Salt and its subcomponents
  • Explore best practices for Salt
Estimated delivery fee Deliver to Luxembourg

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Nov 25, 2016
Length: 378 pages
Edition : 2nd
Language : English
ISBN-13 : 9781786467393
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Estimated delivery fee Deliver to Luxembourg

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

Product Details

Publication date : Nov 25, 2016
Length: 378 pages
Edition : 2nd
Language : English
ISBN-13 : 9781786467393
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 108.97
Learning SaltStack
€29.99
Extending SaltStack
€36.99
Mastering SaltStack
€41.99
Total 108.97 Stars icon

Table of Contents

13 Chapters
1. Essentials Revisited Chevron down icon Chevron up icon
2. Diving into Salt Internals Chevron down icon Chevron up icon
3. Managing States Chevron down icon Chevron up icon
4. Exploring Salt SSH Chevron down icon Chevron up icon
5. Managing Tasks Asynchronously Chevron down icon Chevron up icon
6. Taking Advantage of Salt Information Systems Chevron down icon Chevron up icon
7. Taking Salt Cloud to the Next Level Chevron down icon Chevron up icon
8. Using Salt with REST Chevron down icon Chevron up icon
9. Understanding the RAET and TCP Transports Chevron down icon Chevron up icon
10. Strategies for Scaling Chevron down icon Chevron up icon
11. Monitoring with Salt Chevron down icon Chevron up icon
12. Exploring Best Practices Chevron down icon Chevron up icon
13. Troubleshooting Problems Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.6
(5 Ratings)
5 star 80%
4 star 0%
3 star 20%
2 star 0%
1 star 0%
PW Feb 14, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
That is how you start with Salt
Amazon Verified review Amazon
Amazon Customer Nov 01, 2018
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
As expected
Amazon Verified review Amazon
Ted O'Hayer Feb 09, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Does a great job of diving into Salt's internals, not just the CM/states component. Helped me treat salt as an orchestration platform and build cool stuff on top of it.
Amazon Verified review Amazon
jc Aug 23, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
While there is a lot of documentation on the saltstack web site it is difficult to know how to begin learning about saltstack. This book leads you through the basics. It is a good start for a novice on saltstack. You will probably need some background in python to get the most from this book but it is probably not a necessity
Amazon Verified review Amazon
Thomas S Hatch Jan 17, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book does a fantastic job of going over the depth of the Salt project. Salt comes with a lot of powerful systems that are not exposed in the more simple use cases of Salt and this book does a great job of exposing this functionality.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela