Saltstack 简明教程
SaltStack - Overview
在本章中,我们将学习 SaltStack 的基础知识。SaltStack 的远程执行能力允许管理员并行在多台机器上运行命令,并支持灵活的目标系统。Salt 配置管理建立了一个主服务器-服务端模型,以便快速、轻松、灵活、安全地使基础设施组件与给定策略保持一致。
In this chapter, we will learn the basics of SaltStack. SaltStack’s remote execution capabilities allow administrators to run commands on various machines in parallel with a flexible targeting system. Salt configuration management establishes a master-minion model to quickly, very easily, flexibly and securely bringing infrastructure components in line with a given policy.
What is SaltStack?
Salt 是一款功能非常强大的自动化框架。Salt 架构基于远程执行命令的想法。所有网络都是围绕远程执行的某些方面而设计的。这可能仅仅是要求 Remote Web Server 显示一个静态网页,也可能复杂到使用 shell 会话对远程服务器交互式地发出命令。Salt 是复杂类型远程执行的一个示例。
Salt is a very powerful automation framework. Salt architecture is based on the idea of executing commands remotely. 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. Salt is an example of one of the more complex types of remote execution.
Salt 旨在允许用户显式地针对多台机器并直接向其发出命令。Salt 基于主服务器的概念,它控制一个或多个 Minions 。命令通常从主服务器发出到目标服务端组,然后这些服务端执行命令中指定的任务,再将结果数据返回给主服务器。主服务器和服务端之间的通信通过 ZeroMQ message bus 进行。
Salt is designed to allow users to explicitly target and issue commands to multiple machines directly. 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 then return the resulting data back to the Master. Communications between a master and minions occur over the ZeroMQ message bus.
SaltStack 模块与受支持的服务端操作系统进行通信。 Salt Master 在默认情况下在 Linux 上运行,但任何操作系统都可以作为一个服务端,并且当前 Windows、VMware vSphere 和 BSD Unix 变体都得到了很好的支持。Salt 主服务器和服务端使用密钥进行通信。当服务端首次连接到主服务器时,它会自动将密钥存储在主服务器上。SaltStack 还提供 Salt SSH ,它提供“无代理”系统管理。
SaltStack modules communicate with the supported minion operating systems. The Salt Master runs on Linux by default, but any operating system can be a minion, and currently Windows, VMware vSphere and BSD Unix variants are well supported. The Salt Master and the minions use keys to communicate. When a minion connects to a master for the first time, it automatically stores keys on the master. SaltStack also offers Salt SSH, which provides an “agent less” systems management.
Need for SaltStack
SaltStack 专为速度和规模而构建。这就是为何其被用于管理 LinkedIn、WikiMedia 和 Google 中拥有数万台服务器的大型基础设施的原因。
SaltStack is built for speed and scale. This is why it is used to manage large infrastructures with tens of thousands of servers at LinkedIn, WikiMedia and Google.
想象一下,您有多台服务器,并且想对这些服务器做一些事情。您需要登录到每台服务器上,然后逐一在每台服务器上做这些事情,之后您可能还想做一些复杂的事情,比如安装软件,然后根据某些特定条件配置该软件。
Imagine that you have multiple servers and want to do things to those servers. You would need to login to each one and do those things one at a time on each one and then you might want to do complicated things like installing software and then configuring that software based on some specific criteria.
我们假设您有十台甚至 100 台服务器。想象一下,一次登录每台服务器,在 100 台机器上发出相同的命令,然后编辑所有 100 台机器上的配置文件,这将成为一项非常繁琐的任务。为解决这些问题,您会希望仅通过键入一个命令便立即更新所有服务器。SaltStack 正好为您提供了所有此类问题的解决方案。
Let us assume you have ten or maybe even 100 servers. Imagine logging in one at a time to each server individually, issuing the same commands on those 100 machines and then editing the configuration files on all 100 machines becomes very tedious task. To overcome those issues, you would love to update all your servers at once, just by typing one single command. SaltStack provides you exactly the solution for all such problems.
Features of SaltStack
SaltStack 是一款开源配置管理软件和远程执行引擎。Salt 是一款命令行工具。尽管是用 Python 编写的,但 SaltStack 配置管理与语言无关,且非常简单。Salt 平台使用 push 模型通过 SSH 协议执行命令。默认的配置系统是 YAML 和 Jinja templates 。Salt 的主要竞争对手是 Puppet 、 Chef 和 Ansible 。
SaltStack is an open-source configuration management software and remote execution engine. Salt is a command-line tool. While written in Python, SaltStack configuration management is language agnostic and simple. Salt platform uses the push model for executing commands via the SSH protocol. The default configuration system is YAML and Jinja templates. Salt is primarily competing with Puppet, Chef and Ansible.
与其他竞争工具相比,Salt 提供了许多特性。下面列出了一些重要的特性。
Salt provides many features when compared to other competing tools. Some of these important features are listed below.
-
Fault tolerance − Salt minions can connect to multiple masters at one time by configuring the master configuration parameter as a YAML list of all the available masters. Any master can direct commands to the Salt infrastructure.
-
Flexible − The entire management approach of Salt is very flexible. It can be implemented to follow the most popular systems management models such as Agent and Server, Agent-only, Server-only or all of the above in the same environment.
-
Scalable Configuration Management − SaltStack is designed to handle ten thousand minions per master.
-
Parallel Execution model − Salt can enable commands to execute remote systems in a parallel manner.
-
Python API − Salt provides a simple programming interface and it was designed to be modular and easily extensible, to make it easy to mold to diverse applications.
-
Easy to Setup − Salt is easy to setup and provides a single remote execution architecture that can manage the diverse requirements of any number of servers.
-
Language Agnostic − Salt state configuration files, templating engine or file type supports any type of language.
Benefits of SaltStack
Salt 既简单又是一个功能丰富的系统,它提供了许多好处,可以总结如下 −
Being simple as well as a feature-rich system, Salt provides many benefits and they can be summarized as below −
-
Robust − Salt is powerful and robust configuration management framework and works around tens of thousands of systems.
-
Authentication − Salt manages simple SSH key pairs for authentication.
-
Secure − Salt manages secure data using an encrypted protocol.
-
Fast − Salt is very fast, lightweight communication bus to provide the foundation for a remote execution engine.
-
Virtual Machine Automation − The Salt Virt Cloud Controller capability is used for automation.
-
Infrastructure as data, not code − Salt provides a simple deployment, model driven configuration management and command execution framework.
Introduction to ZeroMQ
Salt 基于 ZeroMQ 库,它是一款可嵌入的网络库。它是一款轻量级且快速的通信库。基本实现采用 C/C++ ,并且提供了针对数种语言(包括 Java 和 .Net )的原生实现。
Salt is based on the ZeroMQ library and it is an embeddable networking library. It is lightweight and a fast messaging library. The basic implementation is in C/C++ and native implementations for several languages including Java and .Net is available.
ZeroMQ 是无代理、点对点的消息处理功能。ZeroMQ 允许您轻松设计复杂的通信系统。
ZeroMQ is a broker-less peer-peer message processing. ZeroMQ allows you to design a complex communication system easily.
ZeroMQ 随附以下五种基本模式:
ZeroMQ comes with the following five basic patterns −
-
Synchronous Request/Response − Used for sending a request and receiving subsequent replies for each one sent.
-
Asynchronous Request/Response − Requestor initiates the conversation by sending a Request message and waits for a Response message. Provider waits for the incoming Request messages and replies with the Response messages.
-
Publish/Subscribe − Used for distributing data from a single process (e.g. publisher) to multiple recipients (e.g. subscribers).
-
Push/Pull − Used for distributing data to connected nodes.
-
Exclusive Pair − Used for connecting two peers together, forming a pair.
ZeroMQ 是一款高度灵活的网络工具,可用于在集群、云和其他多系统环境中交换消息。ZeroMQ 是 SaltStack 中展示的 default transport library 。
ZeroMQ is a highly flexible networking tool for exchanging messages among clusters, cloud and other multi system environments. ZeroMQ is the default transport library presented in SaltStack.
SaltStack - Architecture
SaltStack 的架构旨在与任意数量的服务器一起使用,从本地网络系统到不同数据中心的其他部署。该架构是一种简单的服务器/客户端模型,所需的功能构建在单个守护程序集中。
The architecture of SaltStack is designed to work with any number of servers, from local network systems to other deployments across different data centers. Architecture is a simple server/client model with the needed functionality built into a single set of daemons.
看看以下说明。它显示了 SaltStack 架构的不同组件。
Take a look at the following illustration. It shows the different components of SaltStack architecture.

-
SaltMaster − SaltMaster is the master daemon. A SaltMaster is used to send commands and configurations to the Salt slaves. A single master can manage multiple masters.
-
SaltMinions − SaltMinion is the slave daemon. A Salt minion receives commands and configuration from the SaltMaster.
-
Execution − Modules and Adhoc commands executed from the command line against one or more minions. It performs Real-time Monitoring.
-
Formulas − Formulas are pre-written Salt States. They are as open-ended as Salt States themselves and can be used for tasks such as installing a package, configuring and starting a service, setting up users or permissions and many other common tasks.
-
Grains − Grains is an interface that provides information specific to a minion. The information available through the grains interface is static. Grains get loaded when the Salt minion starts. This means that the information in grains is unchanging. Therefore, grains information could be about the running kernel or the operating system. It is case insensitive.
-
Pillar − A pillar is an interface that generates and stores highly sensitive data specific to a particular minion, such as cryptographic keys and passwords. It stores data in a key/value pair and the data is managed in a similar way as the Salt State Tree.
-
Top File − Matches Salt states and pillar data to Salt minions.
-
Runners − It is a module located inside the SaltMaster and performs tasks such as job status, connection status, read data from external APIs, query connected salt minions and more.
-
Returners − Returns data from Salt minions to another system.
-
Reactor − It is responsible for triggering reactions when events occur in your SaltStack environment.
-
SaltCloud − Salt Cloud provides a powerful interface to interact with cloud hosts.
-
SaltSSH − Run Salt commands over SSH on systems without using Salt minion.
在下一章节中,我们将详细了解 SaltStack 的各种竞争对手及其特性。
In the next chapter, we will learn in detail about the various competitors of SaltStack and their features.
SaltStack - Competitors
Salt、Puppet、Chef 和 Ansible 是领先的配置管理和编排工具,每个工具都会采用不同的路径实现服务器自动化。它们旨在让配置和维护几十、几百甚至数千台服务器变得更加容易。
Salt, Puppet, Chef, and Ansible are the leading configuration management and orchestration tools, each of which takes a different path to server automation. They were built to make it easier to configure and maintain dozens, hundreds or even thousands of servers.
不妨了解一下 SaltStack 如何主要与 Puppet、Chef 和 Ansible 展开竞争。
Let us understand how SaltStack competes primarily with Puppet, Chef, and Ansible.
Platforms and Support
以下是支持 SaltStack 及其竞争对手的所有平台的列表。
Following is a list of all the platforms that support SaltStack and its competitors.
-
SaltStack − SaltStack software runs on and manages many versions of Linux, Windows, Mac OS X and UNIX.
-
Puppet − Red Hat Enterprise Linux, CentOS, Oracle Linux, Scientific Linux, SUSE Linux Enterprise Server and Ubuntu.
-
Chef − Chef is supported on multiple platforms such as AIX, RHEL/CentOS, FreeBSD, OS X, Solaris, Microsoft Windows and Ubuntu.
-
Ansible − Fedora distribution of Linux, CentOS, and Scientific Linux via Extra Packages for Enterprise Linux (EPEL) as well as for other operating systems.
Origin Language
-
SaltStack − Python
-
Puppet − Ruby
-
Chef − Ruby and its CLI uses ruby-based DSL
-
Ansible − Python
Supported Language
-
SaltStack − Any language
-
Puppet − Ruby
-
Chef − Ruby and its CLI uses ruby-based DSL
-
Ansible − Any language
Web UI
-
SaltStack − Web UI offers views of running jobs, minion status and event logs.
-
Puppet − Web UI handles reporting, inventorying and real-time node management.
-
Chef − Web UI lets you search and inventory nodes, view node activity and assign Cookbooks, roles and nodes.
-
Ansible − Web UI lets you configure users, teams and inventories and apply Playbooks to inventories.
Management Tools
-
SaltStack − SaltStack Enterprise is positioned as the main tool for managing the orchestration of cloud and IT operations, as well as DevOps.
-
Puppet − Puppet comes in two flavors, Puppet Enterprise and Open Source Puppet. In addition to providing functionalities of the Open Source Puppet, Puppet Enterprise also provides GUI, API and command line tools for node management.
-
Chef − CFEngine is the configuration management tool.
-
Ansible − Ansible 1.3 is the main tool for management.
Performance
-
SaltStack − Salt is designed for high-performance and scalability. Salt’s communication system establishes a persistent data pipe between the Salt master and minions using ZeroMQ.
-
Puppet − Secure as well as high-performance and no agents required.
-
Chef − The most apparent struggle for Chef Server is search; Search is slow and is not requested concurrently from clients.
-
Ansible − Secure, high-performance and no agents required.
Price and Value
-
SaltStack − Free open source version. SaltStack Enterprise costs $150 per machine per year.
-
Puppet − Free open source version. Puppet Enterprise costs $100 per machine per year.
-
Chef − Free open source version; Enterprise Chef free for 5 machines, $120 per month for 20 machines, $300 per month for 50 machines.
-
Ansible − Free open source version; Ansible free for 10 machines, then $100 or $250 per machine per year depending on the support you needed.
Usage
-
SaltStack − SaltStack is used by Cisco and Rackspace. It can integrate with any cloud-based platform.
-
Puppet − Puppet is used by Zynga, Twitter, the New York Stock Exchange, PayPal, Disney, Google and so on.
-
Chef − Chef can integrate with cloud-based platforms such as Internap, Amazon EC2, Google Cloud Platform, OpenStack, Microsoft Azure and Rackspace.
-
Ansible − Ansible can deploy to virtualization environments, cloud environments including Amazon Web Services, Cloud Stack, DigitalOcean, and Google Cloud Platform and so on.
SaltStack - Installation
在进行安装之前,需要满足以下要求:
Before moving to installation, you need to have the following requirements −
-
A Linux server (latest Ubuntu server).
-
sudo or root access to this server.
-
使用以下命令安装所有更新:
Install all the updates using the following command −
sudo apt-get update
Install SaltMaster
-
使用以下 apt-get 命令从存储库安装 SaltMaster。
Install the SaltMaster from the repository with the following apt-get command.
sudo apt-get install salt-master
Install Salt Minion
-
使用以下 apt-get 命令从存储库安装 Salt Minion。
Install the Salt minion from the repository with the following apt-get command.
sudo apt-get install salt-minion
Install Salt syndic
-
使用以下 apt-get 命令从存储库安装 Salt Syndic。
Install the Salt syndic from the repository with the following apt-get command.
sudo apt-get install salt-syndic
Master Configuration
Salt 配置非常简单。大多数安装都适用主控的默认配置。配置文件安装在“/etc/salt”目录中,并且以它们各自的组件命名,例如:/etc/salt/master 和 /etc/salt/minion。
Salt configuration is very simple. The default configuration for the master will work for most installations. The configuration files are installed in the ‘/etc/salt’ directory and are named after their respective components, such as − /etc/salt/master and /etc/salt/minion.
#interface: 0.0.0.0
interface: <local ip address>
更新配置文件后,使用以下命令重新启动 Salt 主控。
After updating the configuration file, restart the Salt master using the following command.
sudo service salt-master restart
Minion Configuration
配置 Salt Minion 非常简单。默认情况下,Salt Minion 将尝试连接到 DNS 名称“salt”;如果 Minion 能够正确解析该名称,则不需要配置。重新定义 Minion 配置文件中的“主控”指令,它通常是 /etc/salt/minion ,如下面的代码所示:
Configuring a Salt Minion is very simple. By default a Salt Minion will try to connect to the DNS name “salt”; if the Minion is able to resolve that name correctly, no configuration is required. Redefine the “master” directive in the minion configuration file, which is typically /etc/salt/minion, as shown in the code below −
#master: salt
master: <local ip address>
更新配置文件后,使用以下命令重新启动 Salt Minion。
After updating the configuration file, restart the Salt minion using the command below.
sudo service salt-minion restart
Key Management
对于主控和 Minion 之间的所有通信,Salt 使用 AES Encryption 。主控和 Minion 之间的通信通过受信任的已接受密钥进行验证。
Salt uses AES Encryption for all the communication between the Master and the Minion. The communication between Master and Minion is authenticated through trusted, accepted keys.
salt-key -L
它将生成以下 output −
It will produce the following output −
Accepted Keys:
Denied Keys:
Unaccepted Keys:
<local system name>
Rejected Keys:
通过发布以下命令,接受所有密钥。
Accept all keys by issuing the command below.
sudo salt-key -A
它将生成以下 output −
It will produce the following output −
The following keys are going to be accepted:
Unaccepted Keys:
<local system name>
Proceed? [n/Y] y
Key for minion bala-Inspiron-N4010 accepted.
现在再次发布 salt key listing 命令,
Now again issue the salt key listing command,
salt-key -L
它将生成以下 output −
It will produce the following output −
Accepted Keys:
<local system name>
Denied Keys:
Unaccepted Keys:
Rejected Keys:
Sending Commands
必须通过运行 test.ping 命令验证主控和 Minion 之间的通信。
The communication between the Master and a Minion must be verified by running the test.ping command.
sudo salt '*' test.ping
它将生成以下 output −
It will produce the following output −
<local system name>
True
在此,“ ’ refers to all the minions. Since, we only have one minion – test.ping, it executes the *ping 命令并返回 ping 是否成功。
Here, ‘’ refers to all the minions. Since, we only have one minion – test.ping, it executes the *ping command and returns whether the ping is successful or not.
SaltStack - Creating a Simple Environment
在本章中,我们将创建一个简单的 SaltStack 环境,一个 salt master 和两个 salt minion。此环境将帮助我们在后面的章节中了解 salt 的概念。
In this chapter, we will create a simple SaltStack environment, one salt master and two salt minions. This environment will help us to learn the salt concept in the upcoming chapters.
让我们按照以下步骤创建 SaltStack 环境。
Let us adhere to the following steps to create the SaltStack environment.
Install the VirtualBox Environment
VirtualBox 是一款跨平台虚拟化应用程序。VirtualBox 允许你同时运行多个操作系统。VirtualBox 可以在 Windows、Linux、Macintosh 和 Solaris 上运行。它托管并支持大量 Guest Operating Systems 。
VirtualBox is a cross-platform virtualization application. VirtualBox allows you to run more than one operating system at a time. VirtualBox runs on Windows, Linux, Macintosh and Solaris. It hosts and supports a large number of Guest Operating Systems.
你可以通过访问以下链接下载并安装 VirtualBox − https://www.virtualbox.org/wiki/Downloads
You can download and install VirtualBox by visiting the following link − https://www.virtualbox.org/wiki/Downloads
我们将创建三个虚拟机并使用 VirtualBox 运行它。
We will create three virtual machines and run it using the VirtualBox.
Install Vagrant
Vagrant 提供易于配置的可重现且可移植的工作环境。
Vagrant provides easy to configure, reproducible and portable work environments.
你可以通过访问以下链接下载并安装 Vagrant − https://www.vagrantup.com
You can download and install the Vagrant by visiting the following link − https://www.vagrantup.com
在成功安装 Vagrant 之后,你需要对其进行配置。在文件夹中创建一个名为 Vagrantfile 的单个文件并描述机器的类型和属性。
After the successful installation of Vagrant, you need to configure it. Create a single file named as Vagrantfile in a folder and describe the type of machine and its properties.
Run Vagrant − 要运行 Vagrant,请发出以下命令 −
Run Vagrant − To run the Vagrant, issue the following command −
vagrant up
在运行 vagrant up 之后,Vagrant 会创建并启动已在 Vagrantfile 中定义的那些机器,而在后台使用 VirtualBox。这些机器将持续运行,直到你关闭它们。
After you run vagrant up, Vagrant creates and starts those machines, which are defined in the Vagrantfile using the VirtualBox in the background. These machines will be running until you close them.
Stop Vagrant − 要停止 VirtualBox 中所有正在运行的机器,请键入以下命令 −
Stop Vagrant − To stop all the running machines in the VirtualBox, type the following command −
vagrant halt
Download the Demo Environment
SaltStack 提供了一个简单的演示环境,作为 Vagrant 设置,并且它在 github 中托管。让我们使用以下命令下载设置 −
SaltStack provides a simple demo environment as Vagrant setup and it is hosted in the github. Let us download the setup using the following command −
cd /cd/to/path
git clone https://github.com/UtahDave/salt-vagrant-demo
Start Environment
现在,使用以下命令启动演示环境 −
Now, start the demo environment using the following command −
cd /cd/to/path/salt-vagrant-demo
vagrant up
此命令后,你将看到以下响应 −
After this command, you will see the following response −
result
现在,三个服务器正在运行,一个配置了 Salt master,两个配置了 Salt minion。
Now, three servers are running, one with the salt master configured and two with the salt minion configured.
Run Salt master
使用以下命令登录到 Salt master −
Login to the Salt master using the following command −
vagrant ssh master
现在,使用以下命令切换到 root 用户 −
Now, move to the root user using the command below −
sudo su
现在,我们已成功连接到 Salt master。
Now we have successfully connected to the Salt master.
下面我们介绍 SaltStack 中的一些基本命令。
Let us now go through some of the basic commands in SaltStack.
List out all the Keys
以下命令用于验证 Salt minion 连接以及查看连接是否已接受、拒绝或挂起。
The following command is to verify the Salt minion connections and view whether the connection is accepted, rejected or pending.
salt-key —list-all
它将生成以下 output −
It will produce the following output −
Accepted Keys:
minion1
minion2
Denied Keys:
Unaccepted Keys:
Rejected Keys:
Verify Salt Minions
现在,我们已接受所有密钥,您可以从 Salt master 发送命令来检查 Salt minion 是否正在侦听,
Now, we have accepted all the keys, you can send a command from Salt master to check whether Salt minions are listening or not,
salt '*' test.ping
它将生成以下 output −
It will produce the following output −
minion1:
True
minion2:
True
从上述结果中列出 minion 1 和 minion 2,这意味着 minion 正在正确侦听,否则 minion 可能无法正确响应。
From the above result, list out minion 1 and minion 2, which means minions are listening properly, otherwise minions might now respond properly.
SaltStack - Access Control System
访问控制系统为用户和用户组提供选项,通过权限执行任务。Salt 访问控制系统用来配置对非管理控制界面的访问。可以将这个过程应用于所有系统。这个控制有助于非管理用户执行 Salt 命令。
An Access Control System provides options for a user for a group to execute a task with permissions. A Salt access control system is used to configure access to non-administrative control interfaces. You can apply this process to all the systems. This control helps the non-administrative users to execute the Salt commands.
Salt 界面的类型有以下三种
Salt interfaces are of the following three types −
-
Publisher ACL system
-
External Auth system
-
Peer system
让我们详细了解各个界面。
Let us understand go through each of these interfaces in detail.
Publisher ACL System
发布者 ACL 系统允许除 root 以外的用户在主服务器上对小兵执行 Salt 命令。通过 publisher_acl 配置选项在主服务器配置文件中配置发布者 ACL 系统。它定义如下:
A Publisher ACL system allows access to the users other than root to execute Salt commands on minions from the master. The publisher ACL system is configured in the master configuration file via the publisher_acl configuration option. It is defined as follows −
publisher_acl:
user1:
- .*
user2:
- web*:
- test.*
- pkg.*
在此,
Here,
-
user1 is allowed to execute anything.
-
user2 is allowed to use test and pkg, but only on “web*” minions.
External Auth System
external auth system 用于通过 PAM, LDAP 等外部授权系统在特定小兵上提供执行 salt 命令的访问权限。如下所述,此配置文件定义在主文件中。
The external auth system is used to provide access to execute salt commands on specific minions through external authorization system like PAM, LDAP, etc. This configuration file is defined in the master file as described below.
external_auth:
pam:
user1:
- 'web*':
- test.*
- network.*
user2:
- .*
在此,
Here,
-
user1 is allowed to execute functions in the test and network modules on the minions that match the web* target.
-
user2 is allowed to execute all the functions.
Enable the External Auth System in Command
Salt 服务器提供“–a”选项以启用外部身份验证。
Salt server provides an option ‘–a’ to enable external authentication.
salt -a pam web\* test.ping
此处, -a pam 选项用于启用 PAM 外部身份验证。只要我们执行命令,Salt 服务器会询问身份验证详细信息。若要限制 Salt Server 首次询问身份验证详细信息,我们可以使用 T 选项。此 -T option 会缓存身份验证详细信息,以便在接下来的 12 小时(默认设置)内使用它来对用户进行身份验证。
Here, the -a pam option is used to enable PAM external authentication. Salt Server will ask for authentication details whenever we execute the command. To restrict Salt Server from asking the authentication details for the first time only, we can use the T option. This -T option caches the authentication details for the next 12 hours (default setting) and use it to authenticate the users.
salt -T -a pam web\* test.ping
Peer System
Salt 小兵可以使用对等接口传递命令。对等接口通过主服务器配置文件进行配置,以便通过 peer 配置部分允许小兵从主服务器发送命令,或者允许小兵通过 peer_run 配置使用主服务器执行运行程序。
Salt minions can pass commands using the peer interface. The peer interface is configured through the master configuration file either to allow minions to send commands from the master using the peer configuration section or to allow minions to execute runners from the master using the peer_run configuration.
让我们详细了解这两个配置。
Let us understand both these configurations in detail.
Peer configuration
在主文件中定义的简单配置如下:
The simple configuration to be defined in master file is as below −
peer:
.*:
- .*
此处,它为所有小兵启用通信,但这仅在非常安全的环境中才推荐使用。
Here, It enables communication for all minions, but it is only recommended for very secure environments.
若要将小兵分配到特定 ID,需要按如下所示定义配置:peer -
To assign minions to specific ID’s, the configuration needs to be defined as shown below: peer −
.*domain.com:
- test.*
peer_run Configuration
此配置可允许 Minion 使用 master 文件中的 peer_run 选项在 Master 中执行 Runner。以下示例允许访问所有 Minion 和所有 Runner。
This configuration is to allow minions to execute runners from the master using the peer_run option on the master file. The following example is to allow access to all minions and to all the runners.
peer_run:
.*:
- .*
若要将 Minion 分配给特定 ID,需要定义如下所示的配置:
To assign minions to a specific ID, the configuration needs to be defined as given below −
peer_run:
.*domain.com:
- test.*
How to Execute Commands
若要在所有 Minion 上执行 test.ping ,请使用 salt-call 命令以及 publish.publish 模块。
To execute test.ping on all the minions, use the salt-call command along with the publish.publish module.
salt-call publish.publish \* test.ping
若要执行 runner ,请使用盐调用命令以及 publish.runner 模块。
To execute runner, use the salt-call command along with the publish.runner module.
salt-call publish.runner manage.up
SaltStack - Job Management
Salt 能够与大量的系统进行高速通信。此方法有助于 Salt 构筑一个功能强大的多任务处理系统。Salt 可以在多个系统上运行作业,因此 Salt 使用作业管理技术来管理所有系统上运行的每个作业。本章详细解释了作业管理。
Salt has the capability of high-speed communication with a large number of systems. This approach helps Salt to make a powerful multitasking system. Salt can run jobs on more than one systems, so Salt uses job management technique to manage each job running on all the systems. This chapter explains about job management in detail.
What is a Job ID?
Salt 具有缓存目录 ` cachedir `。在此内部,小 Minion 维护的目录称为 ` proc ` 目录。它位于以下目录 /var/cache/salt/proc 中。
Salt has cache directory, cachedir. Inside this, a directory that minions maintain is called as the proc directory. It is located in the following directory /var/cache/salt/proc.
proc 目录用于维护所有文件。当这些文件被执行时,它们会被分配一个唯一的作业 ID。此作业 ID 有助于识别小 Minion 上当前正在运行的作业,并允许查找作业。
The proc directory is used to maintain all the files. When these files are executed, they assign with a unique job ID. This job id helps to identify the current running jobs on the minion and allow the jobs to be looked up.
SALTUTIL Module
Salt 引入了一个称为 Saltutil 作业管理进程的新模块。该模块包含用于管理作业的不同函数。这些函数用于在 Minion 级别管理作业。对函数的简要描述如下所示:
Salt introduces a new module that is called as the Saltutil job management process. This module contains different functions to manage jobs. These functions are used to manage jobs at the minion level. The functions are described in brief as follows −
-
running − Returns all the running jobs data that are found in the proc directory.
-
find_job − Returns specific data about a certain job based on the job id.
-
signal_job − Allows a given job id(jid) to be sent a signal.
-
term_job − Sends a termination signal for the specified job.
-
kill_job − Sends a kill signal for the specified job.
Jobs Runner
作业运行程序包含使查看数据更轻松、更简洁的函数。它有不同的函数。我们详细讨论其中每个函数。
The jobs runner contains functions to make viewing data easier and cleaner. It has different functions. Let us discuss each of these functions in detail.
ACTIVE Function
Active 函数用于识别哪些作业仍在运行,以及检查哪些系统已完成作业,以及哪些系统仍在等待。它使用以下命令执行:
The Active function is used to identify which jobs are still running and check what systems have completed a job and what systems are still being waited on. It is executed using the following command,
salt-run jobs.active
LOOKUP_JID Function
lookup_jid 运行会显示当前正在查找的工作数据。这些作业由主配置中的 keep_jobs 选项配置。它使用以下命令执行。
The lookup_jid runner will display the data for the current looking job. These jobs are configured via the keep_jobs option in the master configuration. It is executed using the following command.
salt-run jobs.lookup_jid <job id number>
Job Scheduling
调度系统公开主上的任何运行函数或 Minion 上的任何运行程序的执行。
The schedule system exposes the execution of any execution function on minions or any runner on the master.
通过以下方法执行 −
It is performed by the following methods −
-
Schedule − The schedule option in either the master or the minion config files.
-
Minion pillar data − It refreshes the minion pillar data using the saltutil.refresh_pillar command.
-
The schedule state or schedule module.
Salt 状态在 Minion 上执行。您可以传递位置参数,并在 config file 中提供 YAML dict 的命名参数,如下所示。
Salt states are executed on the minion. You can pass the positional arguments and provide a YAML dict of the named arguments in the config file as shown below.
schedule:
job1:
function: saltstate.sls
seconds: 3600
args:
- httpd
kwargs:
test: True
在此, job1 将使用指定参数 httpd 每小时执行函数 saltstate.sls 。 test: True 是 httpd 命令的附加参数,该命令在 saltstate.sls 中定义。
Here, job1 will execute the function saltstate.sls with the specified arguments, httpd for every hour. The test: True is the additional argument for the httpd command that is defined in saltstate.sls.
SaltStack - Salt File Server
Salt 文件服务器是一个无状态 ZeroMQ 服务器。它内置于 Salt 主服务器中。Salt 文件服务器用于将文件从主服务器分发到 minion。它包含不同的模块。让我们在本章中了解一下 Salt 文件服务器、其配置、与 Salt 文件服务器相关的模块、如何在 Python 中访问 Salt 文件服务器,等等。
The Salt file server is a stateless ZeroMQ server. It is built into the Salt master. A Salt file server is used for distributing files from master to minions. It contains different modules. Let us understand the salt file server, its configuration, modules related to the salt file server, how to access the salt file server in python, etc., in this chapter.
File Server Backend
文件服务器后端允许 Salt 文件服务器充当其他文件服务器的透明接口,例如,本地文件系统、Git 版本控制系统,等等。
The file server backend allows the Salt file server to act as a transparent interface to other file server like a local file system, Git version control system, etc.
可以通过在主文件中使用以下配置来启用 Git 文件服务器后端。
A Git file server backend can be enabled by using the following configuration in the master file.
fileserver_backend:
- git
要启用多个后端文件系统,我们可以使用以下配置。
To enable multiple backend file system, we can use the following configuration.
fileserver_backend:
- roots
- git
我们还可以使用相应后端服务器的具体部分,为不同的后端服务器指定附加选项。
We can also specify the additional option for a different backend server using the specific section of the corresponding backend server.
Local File System
要使用此系统,我们必须使用以下代码。
For using this system, we have to use the following code.
file_roots:
base:
- /srv/salt/prod
File Server Configuration
可以在许多根目录内分配 Salt 文件,并通过指定文件路径和要搜索的环境来访问 Salt 文件。各别环境可以跨越多个目录根目录。
Salt files can be allocated within many root directories and accessed by specifying both the file path and the environment to search. The individual environments can span across multiple directory roots.
Environment
默认环境是 base。该环境已定义,当未指定其他环境时可用于下载文件。
The default environment is base. This environment is defined and is used to download files when no other environment is specified.
file_roots:
base:
- /srv/salt/base
您还可以像如下代码中所示使用多个环境。
You can also use multiple environments as shown in the code below.
file_roots:
base:
- /srv/salt/base
dev:
- /srv/salt/dev
- /srv/salt/base
CP Module
CP 模块是用来处理 Salt file server 的主模块。 salt-cp 命令也可以用来分发 Salt 文件服务器提供的文件。
The CP module is the main module to manipulate the Salt file server. The salt-cp command can also be used to distribute files presented by the Salt file server.
GET_FILE
cp.get_file 函数可在 Minion 上用于从 Master 下载文件。它被定义为如下代码块中所示。
The cp.get_file function can be used on the minion to download a file from the master. It is defined as shown in the following code block.
salt '*' cp.get_file salt://vimrc /etc/vimrc
上述命令指导所有 Salt Minion 下载 vimrc 文件并将其复制到 /etc/vimrc 。
The above command instructs all Salt minions to download the vimrc file and copy it to /etc/vimrc.
Enable Template
你可以通过如下方式在 get_file 中启用模板选项 -
You can enable template option in get_file as follows −
salt '*' cp.get_file "salt://vimrc" /etc/vimrc template = jinja
Apply Compression
若要使用压缩,请使用 gzip 命名参数。有效的值为 1 至 9 之间的整数,其中 1 为最小压缩,9 为最大值。
To use compression, use the gzip named argument. The valid values are integers from 1 to 9, where 1 is the minimum compression and 9 is maximum value.
该命令被定义为如下 -
The command is defined as follows −
salt '*' cp.get_file salt://vimrc /etc/vimrc gzip = 5
GET_DIR
cp.get_dir 函数可在 Minion 上用于从 Master 下载整个目录。它被定义在如下代码块中。
The cp.get_dir function can be used on the minion to download an entire directory from the master. It is defined in the following code block.
salt '*' cp.get_dir salt://etc/mysql /etc
cp.get_dir 支持模板渲染和 gzip 压缩参数。如果你需要,可以分配。
The cp.get_dir supports template rendering and gzip compression arguments. If you want, you can assign as well.
FILECLIENT Module
Salt 提供了一个 Python 模块,它有助于访问 Salt 文件服务器。 salt/fileclient.py 模块用于设置从 Minion 到 Master 的通信。
Salt provides a python module that helps to access the salt file server. The salt/fileclient.py module is used to set up the communication from the minion to the master.
获取文件的示例代码如下 -
The sample code to get files is as follows −
import salt.minion
import salt.fileclient
def get_file(path, dest, saltenv = ‘base'):
client = salt.fileclient.get_file_client(__opts__)
return client.get_file(path, dest, true, saltenv)
在此,
Here,
-
opts is available when the module is run in the salt environment. Otherwise, we should provide the configuration path – /etc/salt/minion.
-
path refers to the path of the source file in salt file server.
-
dest refers the destination path of the file.
-
saltenv refers to the environment
在下一章中,我们将了解如何使用 Git 作为文件服务器。
In the next chapter, we will understand how to use Git as the file server.
SaltStack - Git as a File Server
Git 是一个开源分布式版本控制系统。它可用于跟踪任何文件中的更改。Salt 使用 Git 文件服务器从 Git 存储库发送文件。你可以将 Git 配置到 fileserver_backend 列出选项,如果你需要配置一个或多个存储库,则可以使用 gitfs_remotes 选项进行配置。
Git is an open-source distributed version control system. It can be used to keep a track of changes in any files. Salt sends files from Git repositories using the Git file server. You can configure Git to the fileserver_backend list option and if you need to configure one or more repositories, you can do so by using the gitfs_remotes option.
本章介绍如何安装和配置 Git 文件服务器。在进行安装之前,你必须具备以下先决条件:
This chapter explains about how to install and configure the Git file server. Before moving towards the installation, you must have the following prerequisites.
Salt Server Prerequisites for Using Git
最低要求的盐服务器使用 Git 作为文件服务器如下 −
The minimal requirement for the salt server to use Git as the file server is as follows −
-
pygit2
-
Dulwich
使用主配置文件中的 gitfs_provider 参数配置 Pygit2 和 Dulwich。如果在主文件中未配置 gitfs_provider ,则 Salt 将优先选择 pygit2(如果可用合适的版本),其次是 GitPython 和 Dulwich 。
Pygit2 and Dulwich are configured using the gitfs_provider parameter in the master config file. If gitfs_provider is not configured in the master file then Salt will prefer pygit2, if the suitable version is available, followed by GitPython and Dulwich.
Install pygit2
以下命令用于在 Fedora 和 Ubuntu 系统中安装 pygit2 −
The following commands are used to install pygit2 in the Fedora and Ubuntu based systems −
-
Fedora-based system
yum install python-pygit2
-
Ubuntu-based system
apt-get install python-pygit2
此处,pygit2 的最低受支持版本为 0.20.3。
Here, the minimum supported version of pygit2 is 0.20.3.
Install GitPYTHON
可以使用 yum / apt command 轻松在主设备上安装 GitPython,如下所示。
GitPython can be easily installed on the master using the yum / apt command as shown below.
-
Fedora-based system
yum install GitPython
-
Ubuntu-based system
apt-get install python-git
Install DULWICH
使用 yum 命令,可以将 Dulwich 轻松安装到主服务器。
Dulwich can be easily installed on the master using the yum command.
-
Fedora-based system
yum install python-dulwich
-
Ubuntu-based system
apt-get install python-dulwich
现在,我们已经安装 Git 文件服务器的所有依赖项。现在让我们使用 fileserver_backend 文件中的 master config 部分配置该 Git 文件服务器。
Now, we have installed all the dependencies for the Git file server. Let us now configure this Git file server using the fileserver_backend section in the master config file.
Backend Configuration
为了使用 Git 文件服务器,你需在主配置文件中的 fileserver_backend 列表中添加 Git。详述如下−
In order to use the Git file server, you need to add Git in the fileserver_backend list in the master config file. It is described as follows −
fileserver_backend:
- git
让我们进一步了解如何在远程配置中配置 Git 文件服务器。
Let us further understand how to configure the Git file server in a remote configuration.
gitfs_remotes Configuration
你可以为 master 文件中的 gitfs_remotes 配置指定任何一个或全部 URL,如 git://、https://、file:// 或 ssh://。这用于搜索请求的文件。
You can specify any one or all of the URLs such as git://, https://, file://, or ssh:// for the gitfs_remotes configuration in the master file. This is used to search for the requested files.
简单的 https URL 规范如下所示。
The simple https URL specification is defined below.
gitfs_remotes:
- https://github.com
可以在如下所示,完成 ssh 配置。
The ssh configuration can be done as shown below.
gitfs_remotes:
- git@github.com:user1/sample.git
- ssh://user@domain.tld/path/to/sample.git
现在,我们已经使用两个配置选项 fileserver_backend 和 gitfs_remotes 配置了 Git 文件服务器。
Now, we have configured the Git file server using the two options fileserver_backend and gitfs_remotes.
Multiple Remotes Configuration
以下命令用于主文件中的 gitfs_remotes 中的多次配置。
The following command is used for multiple configuration in gitfs_remotes in the master file.
gitfs_remotes:
- git://github.com/sample/sample1.git
- https://github.com/sample/sample2.git
- file:///root/user/sample
这里,版本库 sample1.git, sample2.git, 和 sample.doc 可能有以下文件。
Here, the repositories sample1.git, sample2.git, and sample.doc may have the following files.
sample1.git:
top.sls
sample2.git
edit/vimrc
sample.doc
edit/vimrc
SaltStack - Using MinionFS as the File Server
MinionFS 是 Salt 为 Minion 提供的特殊文件服务器,用于在它们之间交换文件。MinionFS 提供的文件是 Minion 有意共享的文件。要共享文件,Minion 必须遵循以下步骤。
The MinionFS is a special file server provided by Salt for the minions to exchange the files between them. The files served by the MinionFS are the files intentionally shared by minions. To share the files, a Minion has to follow steps given below.
-
Source minion has to push the file to the salt master using the cp.push function.
-
Once the files are pushed by the source minion, the deployed files can be accessed by any other minion using the MinionFS file server.
Enable Pushing
默认情况下,禁用 Minion 将文件推送到主机。要接受来自 Minion 的文件,主机在配置文件中需要有 “file_recv” 选项,并且其值必须设置为 True 。默认情况下,“file_recv” 的值是 false 。
By default, pushing the files by minions to a master is disabled. To accept the files from minions, the master needs to have the “file_recv” option in the config file and its value must be set to True. By default, the value if “file_recv” is false.
file_recv: True
启用该选项后,重启主机服务。
Once the option is enabled, restart the master service.
Pushing Files
Minion 可以将文件推送到主机。它由 cp.push 函数执行。此 cp.push 函数提供了一个简单的机制,供 Minion 使用 Minion id 推送文件。
Minions can push the files to the master. It is performed by the cp.push function. This cp.push function provides an easy mechanism to push the files by minion using the minion id.
salt 'minion-id' cp.push /path/to/the/file
这里,Minion id 用于识别哪个 Minion 正在推送文件。此命令将把文件存储在 master’s cachedir 下的 minions 子目录中。 通常,路径为 – /var/cache/salt/master/minions。
Here, the minion-id is used to identify which minion is pushing the file. This command will store the file in a subdirectory named minions under the master’s cachedir. Usually, the path is – /var/cache/salt/master/minions.
对于 Minion, m1 和文件 – /var/log/mylog.txt,文件将存储在 – /var/cache/salt/master/minions/m1/var/log/mylog.txt 中。
For minion, m1 and the file – /var/log/mylog.txt, the file will be stored in the – /var/cache/salt/master/minions/m1/var/log/mylog.txt.
Enable MinionFS
要启用 MinionFS,只需在文件服务器后端设置中添加 minion ,如下面的代码块所示。
To enable the MinionFS, simply add minion in the fileserver backend setting as shown in the following code block.
fileserver_backend:
- roots
- minion
启用 MinionFS 后,Minion 推送的文件可用为 −
Once MinionFS is enabled, the minion pushed files are available as −
salt://<minion-id>/path/to/pushed/file
对于minion m1 和推送文件 – /var/log/mylog.txt, 将从 salt://m1/var/log/mylog.txt 提供推送文件。
For minion, m1 and the pushed file – /var/log/mylog.txt, the pushed file will be served from salt://m1/var/log/mylog.txt.
可使用以下配置在特殊目录中装载此 minionFS。它会将 minionFS 文件与其它文件分开,并帮助整理 minion 文件。
This minionFS can be mounted in a special directory using the following configuration. It will separate the minionFS files from other files and will help in organizing the minion files.
minionfs_mountpoint: salt://minionfs
对于以上配置,该文件将作为 minionfs 目录中的一项展示为 – salt://minionfs/m1/var/log/mylog.txt
For the above configuration, the file will available under the minionfs directory as – salt://minionfs/m1/var/log/mylog.txt
MinionFS Advanced Options
MinionFS 还提供选项,以启用/禁用特定 minion 中推送文件的可用性。这些选项是 minionfs_whitelist ,用于启用 minion; minionfs_blacklist ,用于禁用 minion。
The MinionFS also provides an option to enable / disable the availability of pushed files from a certain minion. The options are minionfs_whitelist, to enable minions and minionfs_blacklist, to disable the minions.
minionfs_whitelist:
- webserver
- develop*
- ‘mail\d+.mysite.com'
minionfs_blacklist:
- testing
在以上配置中,除了 testing 之外,所有 minion 都被允许使用 minionFS 共享文件。
In the above configuration, all minions except testing are allowed to share the file using minionFS.
-
Webserver1
-
Minions whose ids matches the regular expression develop *
-
Minions whose ids matches the regular expression mail\d+.mysite.com.
-
Testing
在下一章中,我们将学习如何使用 Salt 进行 Cron。
In the next chapter, we will learn how to use Cron with Salt.
SaltStack - Using Cron with Salt
Salt 可与 Cron 应用程序一起使用。同时使用这两个应用程序可为 Salt 的自动化提供极好的机会。Salt 提供了远程执行命令的选项,而 Cron 允许以预先调度或自动的方式运行。让我们在本章中学习如何同时使用 Cron 和 Salt。
Salt can be used along with the Cron application. Using both applications together provides a great opportunity to automate Salt. While Salt provides an option to execute commands remotely, Cron enables it to run in a pre-scheduled or automated manner. Let us learn how to use Cron and Salt together in this chapter.
What is Cron?
Cron 是 Linux 环境中非常有用的应用程序。它允许预设一个命令或脚本,以便在特定日期和时间运行。它还允许以规则的时间间隔运行一个应用程序,比如每天、每周或每个月的第一天。
Cron is very useful application in the Linux Environment. It enables to preset a command or script to run in a specific date and time. It also enables to run an application in a regular interval, say daily, weekly or every first day of the month.
Cron 在系统启动时启动,并检查 /etc/crontab 文件以获取配置详细信息。/etc/crontab 在单独的行中列示每个应用程序及其时间表,如下所示。
Cron starts when the system starts and check the /etc/crontab file for configuration details. The /etc/crontab has every application and its schedule in a separate line as shown below.
15 * * * * root echo "This command runs at 15 minutes past every hour"
15 10 * * * root echo "This command is run daily at 10:15 am"
每行都有以下七个入口点,它们以空格分隔,如下所示:
Every line has the following seven entry points, which are separated by space and they are as follows −
-
minute − minute of the hour and is between ‘0’ and ‘59’.
-
hour − hour and is specified in the 24-hour clock.
-
day_of_month − Day of the Month and is between 1 and 31. For example, the 10th of each month is 10.
-
month − A month specified and is specified numerically (0-12), or as the name of the month (e.g. May).
-
day_of_week − Day of the week is specified numerically (0-7) or as the name of the day (e.g. Sun).
-
user − User account under which the command runs.
-
cmd − The actual command and its arguments.
在这里,如果没有分配任何内容,* 会替换。
Here, * replaces, if nothing is assigned.
Salt Caller (salt-call)
Salt 提供了一个 CLI (命令行接口) salt-call 来运行本地 minion 系统本身中的模块,而不是使用 salt 命令从主服务器运行。salt call CLI 支持 salt 命令支持的所有选项,但仅在本地运行。
Salt provides a CLI (Command Line Interface), salt-call to run the modules in the local minion system itself instead of from the master server using the salt command. The salt call CLI supports all the options supported by salt command, but run locally.
Salt caller 最初设计为支持调试,但现在可将其用作独立应用程序。
Salt Caller was initially designed to support debugging, but now, it can be used as a standalone application.
salt-call test.ping
Using salt-call in cron
salt-call CLI 可用于使用 Cron 安排 Salt 操作。例如,要在每天午夜检查 minion 的状态,我们可以使用 salt-call 以及选项 --state.apply,如下所示。
The salt-call CLI is useful to schedule salt operation using Cron. For example, to check the state of the minion every day at midnight, we can use salt-call along with the option – state.apply as shown below.
/etc/crontab
/etc/crontab
PATH = /bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:/opt/bin
0 0 * * * salt-call state.apply
在此,
Here,
-
The state.apply function will check the salt configuration file for the minion and check whether all action defined for the minion is properly configured.
-
Setting the path is a good practice because sometimes the salt command may not be available in the system path.
在下一章中,我们将学习远程执行,这是 Salt 的一个核心概念。
In the next chapter, we will learn Remote Execution, which is a core concept of Salt.
SaltStack - Remote Execution
Salt 的核心概念之一是远程执行。Salt 可以在数秒内跨数千个系统执行命令。Salt 使用自己的命令来实现该功能。我们现在了解本章中用于远程执行的不同 Salt 命令。
One of the core concepts of Salt is remote execution. Salt can execute commands across thousands of systems in a matter of seconds. Salt uses its own command to do this functionality. Let us now understand the different Salt commands for remote execution in the chapter.
Salt Command
Salt 命令允许 Salt Master 与一个或多个 Salt minions 进行通信。基本语法如下所示,
Salt command enables the Salt master to communicate with one or more Salt minions. The basic syntax is as follows,
salt '<target>' <module.function> [arguments]
上面的命令语法包含以下三个主要组件。
The above command syntax consists of the following three main components.
-
target − It determines which systems is applied by the command.
-
module.function − It is a command. Commands consists of a module and function.
-
arguments − Additional data needed for calling the function.
让我们详细了解每个组件。
Let us understand each of the components in detail.
What is the Target Component?
目标是一个组件,它允许您过滤微件(托管系统)以运行函数。下面定义了一个使用目标组件的简单命令。
Target is a component, which allows you to filter minions (managed system) to run the function. A simple command using the target component is defined below.
salt '*' test.ping
它将生成以下 output −
It will produce the following output −
minion2:
True
minion1:
True
在这里,目标 ‘ ’* 表示所有受管理的系统。此处的 ‘ test ’ 是一个模块,而 ping 是一个函数。这用于测试远程系统中的 ping 服务。我们将在后续章节中了解不同的模块及其函数。
Here, the target ‘’* represents all the managed systems. The ‘test’ here is a module and ping is a function. This is used to test the ping service in the remote system. We will learn about the different modules and its functions in subsequent chapters.
Targets using ID (minion)
您可以使用目标中的 id 向特定微件发送命令。不要使用 ' ' , you can replace it using *minion id 。它在下面定义。
You can send a command to a specific minion using its id in the target. Instead of using '', you can replace it using *minion id. It is defined below.
salt 'minion1’ test.ping
它将生成以下 output −
It will produce the following output −
minion1:
True
Targets using Regular Expression
可以按特定正则表达式过滤目标。它在下面定义。
Targets can be filtered by specific regular expression. It is defined below.
salt -E 'minion[0-9]' test.ping
它将生成以下 output −
It will produce the following output −
minion2:
True
minion1:
True
Module and Functions (module.function)
Salt 可以执行 shell 命令;更新软件包并同时在所有托管系统中分发文件等。Salt 使用模块执行这些操作。Salt 为所有可用功能提供了特殊模块。让我们在本教程中使用一些简单的示例了解不同的 Salt 模块。
Salt can execute shell commands; update packages and distribute files, etc., in all of its managed systems simultaneously. Salt does these operations using modules. Salt has special modules for all the available functionalities. Let us understand the different Salt modules using some simple example in this chapter.
Shell Command
Salt 在多个系统上使用 ` cmd.run ` 命令来远程执行 shell 命令。` cmd ` 是主模块,` run ` 是 ` cmd ` 模块中可用的其中一个函数。` run ` 函数使任何 shell 命令都能在远程系统中执行,如下面的代码块所示。
Salt executes shell commands remotely across multiple systems using the cmd.run command. The cmd is the main module and run is one of the function available in the cmd module. The run function enables any shell command to be executed in the remote system as shown in the code block below.
salt '*' cmd.run 'ls -l /etc'
它将生成以下 output −
It will produce the following output −
minion2:
total 868
drwxr-xr-x 7 root root 4096 Jan 26 22:10 X11
drwxr-xr-x 3 root root 4096 Jan 26 21:02 acpi
-rw-r--r-- 1 root root 2981 Jan 26 20:48 adduser.conf
-rw-r--r-- 1 root root 10 Jan 26 21:04 adjtime
drwxr-xr-x 2 root root 4096 Jan 26 22:10 alternatives
drwxr-xr-x 3 root root 4096 Jan 26 20:53 apm
drwxr-xr-x 3 root root 4096 Jan 26 21:02 apparmor
drwxr-xr-x 9 root root 4096 Jan 26 21:02 apparmor.d
drwxr-xr-x 3 root root 4096 Jan 26 21:02 apport
drwxr-xr-x 6 root root 4096 Jan 29 07:14 apt
drwxr-xr-x 2 root root 4096 Jan 26 22:10 at-spi2
……………
……………
minion1:
total 868
drwxr-xr-x 7 root root 4096 Jan 26 22:10 X11
drwxr-xr-x 3 root root 4096 Jan 26 21:02 acpi
-rw-r--r-- 1 root root 2981 Jan 26 20:48 adduser.conf
-rw-r--r-- 1 root root 10 Jan 26 21:04 adjtime
drwxr-xr-x 2 root root 4096 Jan 26 22:10 alternatives
drwxr-xr-x 3 root root 4096 Jan 26 20:53 apm
drwxr-xr-x 3 root root 4096 Jan 26 21:02 apparmor
drwxr-xr-x 9 root root 4096 Jan 26 21:02 apparmor.d
drwxr-xr-x 3 root root 4096 Jan 26 21:02 apport
drwxr-xr-x 6 root root 4096 Jan 29 07:09 apt
drwxr-xr-x 2 root root 4096 Jan 26 22:10 at-spi2
-rw-r----- 1 root daemon 144 Oct 21 2013 at.deny
-rw-r--r-- 1 root root 2177 Apr 9 2014 bash.bashrc
-rw-r--r-- 1 root root 45 Mar 22 2014 bash_completion
……………
……………
Show Disk Usage
Salt 提供了一个专门模块 ` disk ` 来获取受管系统的完整磁盘详细信息。` diskmodule ` 有一个 ` usage ` 函数来查询详细信息。
Salt provides a special module, disk to get the complete disk details of the managed system. The diskmodule has a usage function to query the details.
salt '*' disk.usage
它将生成以下 output −
It will produce the following output −
minion1:
----------
/:
----------
1K-blocks:
41251136
available:
37852804
capacity:
5%
filesystem:
/dev/sda1
used:
1662420
/dev:
----------
1K-blocks:
503908
available:
503896
capacity:
1%
filesystem:
udev
used:
12
/run:
----------
1K-blocks:
101780
available:
101412
capacity:
1%
filesystem:
tmpfs
used:
368
/run/lock:
----------
1K-blocks:
5120
available:
5120
capacity:
0%
filesystem:
none
used:
0
/run/shm:
----------
1K-blocks:
508884
available:
508872
capacity:
1%
filesystem:
none
used:
12
/run/user:
----------
1K-blocks:
102400
available:
102400
capacity:
0%
filesystem:
none
used:
0
/sys/fs/cgroup:
----------
1K-blocks:
4
available:
4
capacity:
0%
filesystem:
none
used:
0
/vagrant:
----------
1K-blocks:
303114632
available:
252331440
capacity:
17%
filesystem:
none
used:
50783192
minion2:
----------
/:
----------
1K-blocks:
41251136
available:
37852804
capacity:
5%
filesystem:
/dev/sda1
used:
1662420
/dev:
----------
1K-blocks:
503908
available:
503896
capacity:
1%
filesystem:
udev
used:
12
/run:
----------
1K-blocks:
101780
available:
101412
capacity:
1%
filesystem:
tmpfs
used:
368
/run/lock:
----------
1K-blocks:
5120
available:
5120
capacity:
0%
filesystem:
none
used:
0
/run/shm:
----------
1K-blocks:
508884
available:
508872
capacity:
1%
filesystem:
none
used:
12
/run/user:
----------
1K-blocks:
102400
available:
102400
capacity:
0%
filesystem:
none
used:
0
/sys/fs/cgroup:
----------
1K-blocks:
4
available:
4
capacity:
0%
filesystem:
none
used:
0
/vagrant:
----------
1K-blocks:
303114632
available:
252331440
capacity:
17%
filesystem:
none
used:
50783192
Network Interfaces
Salt 提供了一个单独的模块、网络和函数,模块内的接口用来查询受管系统的网络接口信息。
Salt provides a separate module, network and function, interfaces inside the module to query the network interface information about the managed systems.
salt '*' network.interfaces
它将生成以下 output −
It will produce the following output −
minion1:
----------
eth0:
----------
hwaddr:
08:00:27:04:3e:28
inet:
|_
----------
address:
10.0.2.15
broadcast:
10.0.2.255
label:
eth0
netmask:
255.255.255.0
inet6:
|_
----------
address:
fe80::a00:27ff:fe04:3e28
prefixlen:
64
scope:
link
up:
True
eth1:
----------
hwaddr:
08:00:27:34:10:52
inet:
|_
----------
address:
192.168.50.11
broadcast:
192.168.50.255
label:
eth1
netmask:
255.255.255.0
inet6:
|_
----------
address:
fe80::a00:27ff:fe34:1052
prefixlen:
64
scope:
link
up:
True
lo:
----------
hwaddr:
00:00:00:00:00:00
inet:
|_
----------
address:
127.0.0.1
broadcast:
None
label:
lo
netmask:
255.0.0.0
inet6:
|_
----------
address:
::1
prefixlen:
128
scope:
host
up:
True
minion2:
----------
eth0:
----------
hwaddr:
08:00:27:04:3e:28
inet:
|_
----------
address:
10.0.2.15
broadcast:
10.0.2.255
label:
eth0
netmask:
255.255.255.0
inet6:
|_
----------
address:
fe80::a00:27ff:fe04:3e28
prefixlen:
64
scope:
link
up:
True
eth1:
----------
hwaddr:
08:00:27:a7:31:8e
inet:
|_
----------
address:
192.168.50.12
broadcast:
192.168.50.255
label:
eth1
netmask:
255.255.255.0
inet6:
|_
----------
address:
fe80::a00:27ff:fea7:318e
prefixlen:
64
scope:
link
up:
True
lo:
----------
hwaddr:
00:00:00:00:00:00
inet:
|_
----------
address:
127.0.0.1
broadcast:
None
label:
lo
netmask:
255.0.0.0
inet6:
|_
----------
address:
::1
prefixlen:
128
scope:
host
up:
True
sys.doc Execution Module
Salt 函数可以被发送到 ` sys.doc ` 执行模块。这被用来直接从命令行获取任何模块的详细信息。Salt 函数是自文档的。可以通过小 Minion 通过 sys.doc() 函数检索所有函数文档,该函数如下所述。
Salt functions can be sent to the sys.doc execution module. This is used to get the details on any module directly from the command line. The Salt functions are self-documenting. All the function documentation can be retrieved from the minions via the sys.doc() function, which is defined below.
salt '*' sys.doc
Arguments for a Function Call
参数用来为函数调用提供附加数据。下面给出简单参数示例。
Arguments are used to provide additional data for the function call. A simple argument example is given below.
salt '*' sys.doc pkg.install
此处,` pkg.install ` 参数是安装特定软件包的模块。
Here, the argument pkg.install is a module to install specific packages.
Python Function
参数是函数的空间分隔参数。它允许 python 代码被传递为参数,如下所示。
Arguments are space-delimited parameters to the function. It allows the python code to be passed as arguments as given below.
salt '*' cmd.exec_code python 'import sys;print sys.version'
它将生成以下 output −
It will produce the following output −
minion2:
2.7.6 (default, Oct 26 2016, 20:30:19)
[GCC 4.8.4]
minion1:
2.7.6 (default, Oct 26 2016, 20:30:19)
[GCC 4.8.4]
同样,您也可以使用可选关键字和 ` YAML ` 格式。
Similarly, you can use optional keywords and the YAML format as well.
SaltStack - Configuration Management
配置管理是 SaltStack 中最重要的概念之一。它用于创建可重用的配置模板,称为 state 。状态描述将系统组件或应用程序置于已知配置所需的一切。
Configuration management is one of the most significant concept in SaltStack. It is used to create a reusable configuration template, called a state. The state describes everything required to put a system component or an application into a known configuration.
Salt State
Salt 状态是对系统特定部分的可重用配置。状态更容易理解,并使用简单的 YAML 描述。
Salt state is a reusable configuration for a specific part of a system. States are easier to understand and described using a simple YAML.
Create a Salt State
Salt 状态很容易创建。让我们在本章中创建一个简单状态。移至目录 “salt-vagrant-demo/saltstack/salt/”,并创建一个名为 samples.sls 的文件,并在其中添加以下行。
Salt states are easy to create. Let us create a simple state in this chapter. Move to the directory “salt-vagrant-demo/saltstack/salt/” and create a file named samples.sls and add the following lines in it.
samples.sls
samples.sls
install_network_packages:
pkg.installed:
- pkgs:
- rsync
- lftp
- curl
现在,保存文件并在 Salt 主控程序中运行以下命令。
Now, save the file and run the following command in the Salt master.
root@saltmaster:/home/vagrant# salt 'minion1’ state.apply samples
这里,我们通过使用 Salt 状态在 Salt Minion minion1 中安装了 rsync, lftp 和 curl 。如果它正常运行,您将看到如下所示的响应。
Here, we installed rsync, lftp and curl through the pkg.installed module using the Salt state in a salt minion, minion1. If it works properly, you could see the response as shown below.
它将生成以下 output −
It will produce the following output −
minion1:
----------
ID: install_network_packages
Function: pkg.installed
Result: True
Comment: All specified packages are already installed
Started: 08:08:48.612336
Duration: 545.385 ms
Changes:
Summary for minion1
------------
Succeeded: 1
Failed: 0
------------
Total states run: 1
Total run time: 545.385 ms
Apply Salt State
现在,我们使用 ‘.sls’ 文件创建了状态,并通过具体调用对其应用。Salt 有一个称为 top.sls 文件的默认状态文件。顶层文件用于将多个状态文件应用于 Salt Minion。顶层文件描述了状态的应用位置。 States 和 Top file 相互配合,共同创建 SaltStack 配置管理功能的核心。
Now that we have created a state using the ‘.sls’ file and applied it by specifically calling it. Salt has a default state file called as the top.sls file. The top file is used to apply multiple state files to Salt minions. The top file describes where states should be applied. Well, States and the Top file work together to create the core of SaltStack’s configuration management capability.
现在,让我们在目录 saltstack/salt 中创建一个简单的 top.sls 文件,并添加以下内容。
Let us now create a simple top.sls file in the directory saltstack/salt and add the following.
top.sls
top.sls
base:
'*':
- common
'minion1':
- samples
这里, state ,通常将 applies 状态 all system 应用于 minion1 。
Here, the state, commonly applies to all system state, samples applies to minion1.
接下来,运行 Salt 主控程序并应用状态,如下所示。
Next, run the Salt master and apply the state as shown below.
root@saltmaster:/home/vagrant# salt '*' state.apply
它将生成以下 output −
It will produce the following output −
minion1:
----------
ID: common_packages
Function: pkg.installed
Result: True
Comment: All specified packages are already installed
Started: 09:33:35.642355
Duration: 588.21 ms
Changes:
Summary for minion1
------------
Succeeded: 1
Failed: 0
------------
Total states run: 1
Total run time: 588.210 ms
minion2:
----------
ID: common_packages
Function: pkg.installed
Result: True
Comment: All specified packages are already installed
Started: 09:33:35.890331
Duration: 602.79 ms
Changes:
Summary for minion2
------------
Succeeded: 1
Failed: 0
------------
Total states run: 1
Total run time: 602.790 ms
Apply Batch Size
如果您连接了很多 Minion,那么您可以限制一次更新的系统数量。这通过使用 –batch-size 选项执行,该选项定义如下。
If you have a large number of connected minions, then you can limit how many systems are updated at once. It is performed by using the –batch-size option, which is defined below.
root@saltmaster:/home/vagrant# salt --batch-size 5 '*' state.apply
它将生成以下 output −
It will produce the following output −
Executing run on ['minion2', 'minion1']
jid:
20170314094638482664
minion1:
----------
ID: common_packages
Function: pkg.installed
Result: True
Comment: All specified packages are already installed
Started: 09:46:41.228519
Duration: 582.24 ms
Changes:
Summary for minion1
------------
Succeeded: 1
Failed: 0
------------
Total states run: 1
Total run time: 582.240 ms
retcode:
0
jid:
20170314094638482664
minion2:
----------
ID: common_packages
Function: pkg.installed
Result: True
Comment: All specified packages are already installed
Started: 09:46:41.153609
Duration: 605.235 ms
Changes:
Summary for minion2
------------
Succeeded: 1
Failed: 0
------------
Total states run: 1
Total run time: 605.235 ms
retcode:
0
Salt State Functions
Salt 状态函数用于在远程系统上安装和配置应用程序。让我们使用 Salt 状态函数安装 “Vim” 包。
Salt state functions are used to install and configure applications on your remote system. Let us install a “Vim” package using the Salt state function.
Create and Apply State Function
在 “salt-vagrant-demo/saltstack/salt/sample.sls” 目录下,创建一个名为 "sample.sls" 的文件,并添加以下内容:
Create a file named “sample.sls” under the directory “salt-vagrant-demo/saltstack/salt/sample.sls” and add the following −
sample.sls
sample.sls
install vim:
pkg.installed:
- name: vim
Vagrant 环境启动后,运行 salt master 并通过运行以下命令应用 sample.sls。
Once, Vagrant environment is up, run the salt master and apply the sample.sls by running the following command.
root@saltmaster:/home/vagrant# sudo salt 'minion2’ state.apply sample
它将生成以下 output −
It will produce the following output −
minion2:
----------
ID: install vim
Function: pkg.installed
Name: vim
Result: True
Comment: Package vim is installed
Started: 15:07:45.752764
Duration: 553.506 ms
Changes:
Summary for minion2
------------
Succeeded: 1
Failed: 0
------------
Total states run: 1
Total run time: 553.506 ms
现在,我们已经添加了一个名为 “Vim” 的包。让我们来利用 Salt 测试方法测试此包。
Now, we have added a package “Vim”. Let us now test the package using the Salt testing method.
Salt State Testing
通过向状态添加 “test = True” 选项,强制进行测试运行。返回的信息将以黄色显示将应用的状态,而结果将报告为 “None”。
The test run is mandated by adding the “test = True” option to the states. The return information will show states that will be applied in yellow and the result is reported as ‘None’.
用于测试状态的命令如下:
The following command is used to test the state −
root@saltmaster:/home/vagrant# sudo salt 'minion2’ state.apply sample test = True
它将生成以下 output −
It will produce the following output −
minion2:
----------
ID: install vim
Function: pkg.installed
Name: vim
Result: True
Comment: Package vim is already installed
Started: 15:07:45.752764
Duration: 553.506 ms
Changes:
Summary for minion2
------------
Succeeded: 1
Failed: 0
------------
Total states run: 1
Total run time: 553.506 ms
SaltStack ─ Pillar Component
Pillar 是实现 Salt 状态可重用性的重要组成部分。它用于为使用目标分配的 minion 定义安全数据。Salt pillar 数据存储端口、文件路径、配置参数和密码等值。
Pillar is an essential component to make Salt states reusable. It is used to define secure data for minions assigned using targets. Salt pillar data stores values such as ports, file paths, configuration parameters and passwords.
Pillar config File
pillar_roots 的配置在主配置文件中如下所示:
The configuration for the pillar_roots in the master config file is shown below −
pillar_roots:
base:
- /srv/pillar
此处,文件位于 “/srv/pillar” 目录中。
Here, the file is in the “/srv/pillar” directory.
考虑位于 /srv/pillar/top.sls 中的 top 文件具有以下结构:
Consider, the top file located in /srv/pillar/top.sls has the following structure −
base:
'*':
- default
现在,移至位于 /srv/pillar/default.sls 的 default.sls 文件,并添加以下代码。
Now, move to the default.sls file located in /srv/pillar/default.sls and add the following code.
# Default pillar values
apache
git
保存文件后,刷新 pillar 以更新所有更改。
After saving the file, refresh the pillar to update all the changes.
Refreshing the Pillar
可以使用以下命令刷新 pillar。
You can refresh the pillar using the following command.
root@saltmaster:/home/vagrant# salt '*' saltutil.refresh_pillar
上述命令用于刷新所有 minion 上的 Salt pillar 数据。
The above command is used to refresh the Salt pillar data on all the minions.
List Pillar Data
若要列出 pillar 数据,可以使用以下命令。
To list out the pillar data, you can use the command given below.
root@saltmaster:/home/vagrant# salt '*' pillar.ls
它将生成以下 output −
It will produce the following output −
minion2:
- apache
- git
minion1:
- apache
- git
Pillar Items
设置 pillar 后,可以通过 pillar 模块在 minion 上查看数据。可以通过下面定义的函数 pillar.items 来访问它。
Once the pillar is setup, the data can be viewed on the minion via the pillar module. It can be accessed through the function pillar.items, which is defined below.
root@saltmaster:/home/vagrant# salt '*' pillar.items
它将生成以下 output −
It will produce the following output −
minion2:
----------
apache:
httpd
git:
git
minion1:
----------
apache:
httpd
git:
git
SaltStack – Include Component
“Include” 组件用于在多个位置定义相同配置任务。这样很容易执行。在状态文件顶部,使用以下格式添加包含项:
The ‘Include’ component is used to define the same configuration task in multiple places. It is easy to perform. At the top of your state file, add an include using the following format −
include:
- state file 1
- state file 2
此处, state file 1 和 state file 2 是你想要包含的 SLS 文件的名称。无需包含 .sls 扩展名。包含的 Salt 状态被插入当前文件的顶部。
Here, state file 1 and state file 2 are the names of the SLS files that you want to include. No need to include the .sls extension. The Included Salt states are inserted at the top of the current file.
Grains Interface
Grains 是一个用于获取有关底层系统信息的界面。收集 grains 以获取有关操作系统、域名、IP 地址、内核、操作系统类型、内存和许多其他系统属性的信息。
Grains is an interface used to derive the information about the underlying system. Grains are collected for the operating system, domain name, IP address, kernel, OS type, memory and many other system properties.
Grains Targeting
在定向小兵时可以使用 Grains 数据,如下代码块所述。
Grain data can be used when targeting minions, which is defined in the following code block.
root@saltmaster:/home/vagrant# salt -G 'os:Ubuntu' test.ping
它将生成以下 output −
It will produce the following output −
minion1:
True
minion2:
True
SaltStack - Logging
日志记录用于跟踪正在运行的软件事件。一个事件由一个描述性消息描述,该消息可选地包含变量数据。Salt 日志记录方法用于获取可能遇到的任何问题。您可以使用特定日志级别进行检查。
Logging is used to track the running software events. An event is described by a descriptive message, which can optionally contain variable data. Salt logging approach is used to get any issues, you may face. You can check out with specific log levels.
Configuration Settings
让我们详细了解日志记录的不同配置设置。
Let us understand the different configuration settings for logging, in detail.
LOG_FILE
Salt 日志记录通过文件传递,该文件包含用于标识的本地路径名称或网络位置。此文件被视为日志文件。
Salt log records are passed through the file, which contains the local path name or the network location for identification. This file is considered as the log file.
log_file: /var/log/salt/master
此处,文件取决于在 master 中执行的二进制文件。同样,您也可以在 minion 中执行,如下所示。
Here, the file dependent of the binary being executed in master. Similarly, you can execute in the minion as well, which is shown below.
log_file: /var/log/salt/minion
您还可以使用远程地址。使用远程地址的语法为 − <file|udp|tcp>://<host|socketpath>:<port-if-required>/<log-facility>。
You can also use remote address. The syntax for using the remote address is − <file|udp|tcp>://<host|socketpath>:<port-if-required>/<log-facility>.
log_file: udp://loghost:port
此处,日志设施默认为 LOG_USER。
Here, the Log-facility defaults to LOG_USER.
LOG_LEVEL
日志级别按数值分配的值排序。Python 库已默认定义了大多数日志级别。除此之外,Salt 还使用更多级别。下面介绍了其中一些级别。
The log levels are ordered in a numerically assigned value. Python library has defined most of the logging levels by default. In addition to that, Salt uses some more levels. Some of the levels are explained below.
-
log_level: error; level value is 40 − It indicates log statement record at error.
-
log_level: quiet; level value is 1000 − It indicates that nothing should be logged at this level.
-
log_level: info; level value is 20 − It indicates the normal log information.
-
log_level: warn; level value is 30 − It indicates log statement record at warning.
-
log_level: debug; level value is 10 − Information useful for debugging both salt implementations and salt code.
-
log_level: trace; level value is 5 − More detailed code-debugging information.
LOG_LEVEL_LOGFILE
它定义要发送到日志文件的消息级别。
It defines the level of messages to send to the log file.
log_level_logfile: info
LOG_DATEFMT
它定义日志日期格式。默认情况下,它表示为 %Y-%m-%d %H:%M:%S。
It defines the log date format. By default, it is represented as %Y-%m-%d %H:%M:%S.
log_datefmt_logfile: '%Y-%m-%d %H:%M:%S'
LOG_FMT_CONSOLE
它定义将消息记录到控制台日志的格式。Salt 使用自定义 LogRecord 属性为控制台日志输出着色。它遵循以下语法 −
It defines the format of the console logging the messages. Salt uses a custom LogRecord attributes to colorize the console log output. It follows the following syntax −
'%(colorlevel)s' # log level name colorized by level
'%(colorname)s' # colorized module name
'%(colorprocess)s' # colorized process number
'%(colormsg)s' # colorized messages name
LOG_FMT_LOGFILE
它定义将消息记录到日志文件的格式。基本语法如下 −
It defines the format of the log file logging the messages. The basic syntax is as follows −
%(asctime)s,%(msecs)03d [%(name)-17s][%(levelname)-8s] %(message)s
LOG_GRANULAR_LEVELS
该级别用于更具体地控制日志级别。
This level is used to control logging levels more specifically.
log_granular_levels:
'salt': 'info'
'salt.modules': ‘trace'
在这里,在“信息”级别的主 Salt 库将 salt.modules 设置为在跟踪级别记录日志。
Here, the Main salt library at the ‘info’ level sets the salt.modules to log at the trace level.
External Logging Handler
Salt 使用 LogStash 和 Sentry 外部日志处理程序进行日志记录。让我们在本章节详细了解它。
Salt uses LogStash and Sentry external log handler for logging. Let us understand about it in detail in this chapter.
LOGSTASH Handler
LogStash 是一个开源的服务器端安全数据处理管道。让我们考虑 Salt 中使用 LogStash 的一个简单 UDP 日志处理程序。
LogStash is an open source; server-side secure data processing pipeline. Let us consider a simple UDP logging handler in Salt that uses LogStash.
在 Salt 主文件中指定以下更改 −
Specify the following changes in the Salt master file −
logstash_udp_handler:
host: 127.0.0.1
port: 9999
version: 1
msg_type: logstash
然后在 Logstash 配置文件中添加更改 −
Then add the changes in the Logstash configuration file −
input {
udp {
port ⇒ 9999
codec ⇒ json
}
}
此处 UDP – 是输入,需要具有 json_event 的格式,而这正是我们通过网络发送的内容。
Here, UDP – is the input that needs to have a format as json_event, which is what we send over the wire.
SENTRY Logging Handler
Sentry 是生产部署中的实时错误跟踪以及用于重现和修复崩溃的信息。主文件中的默认配置在下面定义。
Sentry is real-time error tracking in production deployments and information to reproduce and fix crashes. The default configuration in the master file is defined below.
sentry_handler:
dsn: https://pub-key:secret-key@app.getsentry.com/app-id
log_level: debug
此处,sentry 处理程序的默认日志记录级别为 ERROR,但我们在 sentry_handler 配置密钥下定义了 debug log_level 。
Here, the default logging level for the sentry handler is ERROR, but we defined the debug log_level under the sentry_handler configuration key.
SaltStack - Salt through SSH
Salt 使用 salt-minion 在远程系统中执行命令。这是正常行为。在某些情况下,只能通过 SSH 协议访问远程系统。对于这些情况,Salt 提供了一个仅使用 SSH 协议连接远程系统并在 SSH 层中执行命令的选项。
Salt executes commands in a remote system by using salt-minion. This is the normal behavior. In some scenarios, the remote system can be accessed only by the SSH protocol. For these scenarios, Salt provides an option to connect the remote system using the SSH protocol only and execute the command through the SSH layer.
Salt SSH 非常容易配置。唯一需要的配置是在名为 Roster file 的特殊文件中指定远程系统详细信息。此名册文件通常位于 /etc/salt/roster 。名册文件将包含有关远程系统的所有信息以及如何才能连接到该系统。一旦配置名册文件,所有 Salt 命令都将使用 salt-ssh 而不是 salt 命令执行。
Salt SSH is very easy to configure. The only needed configuration is to specify the remote system details in a special file called as the Roster file. This roster file is normally located in /etc/salt/roster. The roster file will have all the information regarding the remote system and how can we connect to it. Once the roster files are configured, all the Salt commands are executed using the salt-ssh instead of the salt command.
Roster File
名册系统专门为 Salt SSH 设计。它被设计为可插入系统。名册系统的唯一目的是收集有关远程系统的信息。名册文件是一个包含 targets 等远程系统信息 YAML based configuration file 。这些目标是具有预定义属性集的特殊数据结构。名册文件包含一个或多个目标,每个目标都由 Salt ID 标识。
The Roster System is designed specifically for Salt SSH. This is designed as a pluggable system. The sole purpose of the roster system is to gather information about the remote system. The roster file is a YAML based configuration file containing remote system information as targets. These targets are a special data structure with a predefined set of attributes. A roster file contains one or more targets and each target is identified by a Salt ID.
名册文件的基本结构如下 −
The basic structure of the roster file is as follows −
<Salt ID>:
host: <host name>
user: <user name>
passwd: <password of the user>
花名册文件中支持的所有其他属性都是可选的。它们如下所示-
All the other attributes supported by the roster file is optional. They are as follows −
-
port − SSH port number.
-
sudo − whether to run the command via sudo.
-
sudo_user − sudo user name.
-
tty − true if sudo is enabled.
-
priv − private key.
-
timeout − timeout for an SSH connection.
-
minion_opts − dictionary of minion opts.
-
thin_dir − target system’s storage directory for salt components.
-
cmd_umask − umask to force for the salt-call command.
示例名册文件如下-
The sample roster file is as follows −
web:
host: 192.168.2.1
user: webuser
passwd: secret
sudo: True
db:
host: 192.168.2.2
Deploy SSH Keys
Salt SSH将为SSH登录生成默认的公钥/私钥对。默认路径将是/etc/salt/pki/master/ssh/salt-ssh.rsa。可以使用 ssh-copy-id 命令将此秘钥部署到远程系统,如下所示。
Salt SSH will generate a default public/private key pairs for SSH logins. The default path will be /etc/salt/pki/master/ssh/salt-ssh.rsa. This key can be deployed to the remote system using the ssh-copy-id command as shown below.
ssh-copy-id -i /etc/salt/pki/master/ssh/salt-ssh.rsa.pub user@web.company.com
Execute Command
执行salt命令就像将 salt cli 命令更改为 salt-ssh 一样简单,如下所示。
Executing a salt command is as simple as changing the salt cli command into salt-ssh as shown below.
salt-ssh '*' test.ping
Raw Shell Command
Salt SSH提供了一个选项(-r)来在远程系统中执行原始命令,从而绕过了salt模块和功能。
Salt SSH provides an option (-r) to execute a raw command in the remote system bypassing the salt module and functions.
salt-ssh '*' -r 'ls'
Targeting with Salt SSH
Salt SSH中面向远程系统仅支持glob和regex目标。由于Salt SSH是一个独立的模块,因此它现在提供的选项有限,并且将在不久的将来提供更多功能。
Targeting the remote system in Salt SSH supports only glob and regex targets. Since Salt SSH is a separate module, it provides only limited options as of now and will provide more features in the near future.
SaltStack - Salt for Cloud Infrastructure
Salt 提供了一个单独的模块 Salt Cloud ,以便提供 Amazon AWS、Google Compute 等各种云提供商的虚拟机。Salt Cloud 是一个用于配置和管理各种云提供商的 VM 的通用接口。
Salt provides a separate module, Salt Cloud to provide virtual machines of various cloud providers like Amazon AWS, Google Compute, etc. Salt Cloud is a generic interface to configure and manage VMs of various cloud providers.
-
Cloud Config − The main configuration file for Salt Cloud is /etc/salt/cloud and it applies to all the VMs. The main configuration file is called Cloud Config.
-
Cloud Providers − To target specific cloud providers, we can use specific configuration file and they are located in /etc/salt/cloud.providers.d/.conf, these are called as *Cloud Providers.
-
Cloud Profiles − To target a specific VM, we can also use a special configuration file, which applies to that particular VM only and they are located at /etc/salt/cloud.profiles.d/.conf, these are called as *Cloud Profiles.
对于虚拟机,首先应用 Cloud Config 中的设置,然后在 Cloud Providers 中应用,最后由 Cloud Profiles 覆盖。
For a virtual machine, settings in the Cloud Config is applied first and then in the Cloud Providers and finally override is done by the Cloud Profiles.
Installation of Salt Cloud
默认情况下,Salt Cloud 内置于 Salt 中,并且可以随时使用。如果没有,我们可以使用以下命令进行安装。
By default, Salt Cloud is built into the Salt and is readily available. If it is not available, we can install it by using the command below.
pip install salt-cloud
由于 Salt Cloud 是一個單獨的模塊並且在其自己的進程中運行,因此也可以將其安裝在 Salt Minion 系統中,而不是 Salt Master 中。
Since Salt Cloud is a separate module and runs in its own process, it can be installed in the Salt Minion system as well instead of the Salt Master.
Provisioning a Virtual Machine
要置備虛擬機,我們需要定義雲提供商和雲配置文件。一旦創建了這兩者,我們就可以置備一個新的虛擬機來使用它。
To provision a virtual machine, we need to define a cloud provider and a cloud profile. Once both are created, we can provision a new virtual machine for using it.
Cloud Provider
雲主機信息在雲提供商配置文件中配置。通常,需要配置的基本信息是雲驅動程序、用戶名、密碼、私鑰等。讓我們創建一個名為 my-amazon-cloud 的新雲提供商。
Cloud host information are configured in the Cloud provider configuration file. Normally, the basic information, which needs to be configured are cloud driver, username, password, private key, etc. Let us create a new cloud provider named as my-amazon-cloud.
-
Create a file, my-amazon-cloud.conf under /etc/salt/cloud.providers.d/
-
Add a new provider using the ec2 driver.
my-amazon-cloud:
driver: ec2
id: '<AWS_ID>'
key: '<AWS_KEY>'
private_key: /path/to/privatekey.pem
keyname: <name of the key>
securitygroup: default
minion:
master: <master server>
Salt 立即為各種雲主機提供驅動程序,例如 GoGrid、HP Cloud、Google Compute Engine (GCE)、Amazon AWS、Joyent、Linode、OpenNebula、ProfitBricks、Proxmox、Saltify、VexxHost、VMWare 等。
Salt provides drivers for various cloud host out of the box, such as GoGrid, HP Cloud, Google Compute Engine (GCE), Amazon AWS, Joyent, Linode, OpenNebula, ProfitBricks, Proxmox, Saltify, VexxHost, VMWare, etc.
配置雲提供商後,我們可以查詢提供商的可用位置、可用機器映像及其各種大小。
Once the cloud providers are configured, we can query the available location of the provider, available machine images, and its various sizes.
salt-cloud --list-location my-amazon-cloud
salt-cloud --list-images my-amazon-cloud
salt-cloud --list-sizes my-amazon-cloud
Cloud Profile
雲配置文件指定虛擬機映像和大小。它可以在 /etc/salt/cloud.profiles.d/ 下配置。讓我們創建一個簡單的配置文件 simple.conf 。
A Cloud profile specifies the virtual machine image and size. It can be configured under – /etc/salt/cloud.profiles.d/. Let us create a simple profile, simple.conf.
aws_micro:
provider: my-amazon-cloud
image: <image_id>
size: <machine_id e.g. t1.micro>
Virtual Machine
配置好提供程序和配置文件後,我們可以像下面這樣輕鬆地提供一個虛擬機,使用 Salt Cloud。
Once the provider and profiles are configured, we can easily provide a virtual machine using the salt-cloud as shown below.
salt-cloud -p aws_micro master minion1 minion2
其中, p - master、minion1 和 minion2 的配置文件名是新的虛擬機。
Where, p – Profile name master, minion1 and minion2 are the new virtual machines.
可以使用以下命令獲取新創建的虛擬機的詳細信息。
The details of the newly created virtual machine can be obtained by using the following command.
salt-cloud --query
可以使用以下命令銷毀虛擬機 −
The virtual machines can be destroyed using the following command −
slat-cloud -d master minion1
Cloud Map
雲映射是一種特殊格式,可一次創建多個虛擬機。地圖文件的格式是指定配置文件,然後在它下面添加一個虛擬機的列表。
A Cloud Map is a special format to create multiple virtual machines at once. The format of the map file is to specify the profile and then add a list of the virtual machines under it.
示例映射文件如下 −
A sample map file is as follows −
micro:
- web1
- web2
large:
- db1
- db2
地圖文件可以作為參數傳遞給 salt-cloud 命令,以創建虛擬機,如下所示 −
The map file can be passed as an argument to the salt-cloud command to create the virtual machine as follows −
salt-cloud -m /path/to/mapfile
SaltStack - Salt Proxy Minions
有许多设备(如路由器、网络设备等)具有定制操作系统、有限内存和高度安全性考虑。在这些设备中,我们无法安装标准 salt-minion ,随后也无法管理这些系统。然而,Salt 提供了一项创新技术来克服这一制约。
There are lot of devices like router, network gear, etc., having custom OS, limited memory and high security considerations. In those devices, we were not able to install the standard salt-minion and subsequently were unable to manage those systems. However, Salt provides an innovative technology to overcome this constrain.
Salt 有一个单独的模块,即 salt 代理守护进程,它使用远程系统中运行的 REST 服务来控制远程系统。此 REST 服务是使用 Representational State Transfer (REST) 概念编写的基于 HTTP 的网络服务,它们易于实现且易于使用。
Salt has a separate module, salt proxy minion that controls the remote system using the REST service running in the remote system. This REST service is a HTTP based web service written using the Representational State Transfer (REST) concept and they are both easy to implement and easy to consume.
每个设备将有自己的 SDK 和开发环境来编写复杂应用程序。Salt 预期在设备中开发一个 REST 服务,以符合 Salt 接口规范。Salt 还提供了一个 python 模块来编写 REST 网络服务。如果设备支持 python,那么开发 REST 网络服务将很容易。
Every device will have its own SDK and development environment to write complex applications. Salt expects a REST service to be developed in the device as per the Salt interface specification. Salt also provides a python module to write the REST web service. If the device supports python, then it will be easy to develop the REST web service.
一旦在远程系统中开发和部署了 REST 网络服务,就可以配置 Salt,使其使用 REST 网络服务来控制远程设备,而不是使用 salt 守护进程。
Once the REST web service is developed and deployed in the remote system, Salt can be configured to control the remote device using the REST web service instead of the salt minion.
Working Example
让我们使用一个实时工作环境来学习 salt proxy minion 的概念。对于实时环境,我们为服务器端和代理守护进程选择了 Linux 系统。我们将使用 REST 网络服务来控制系统,而不是使用 salt 守护进程。
Let us learn the concept of salt proxy minion using a live working environment. For the live environment, we chose a Linux system for both the master and the proxy minion. We are going to control the system using REST web service instead of salt-minion.
Install and Configure REST Web Service
Salt 提供了一个 REST 网络服务实现的示例,该示例在其 contrib 模块中命名为 proxyminion_rest_example。让我们安装示例网络服务。
Salt provides a sample of the REST web service implementation, which is named as proxyminion_rest_example in its contrib module. Let us install the sample web service.
-
Install ‘bottle’ using the pip. The bottle command is a python web framework to develop web application.
pip install bottle = 0.12.8
-
Download the saltstack/salt-contrib project from github. Otherwise, clone the project using the following command.
git clone https://github.com/saltstack/salt-contrib
-
Open a terminal and go to the salt-contrib directory.
-
This salt-contrib directory will have a folder, proxyminion_rest_example. This folder contains sample implementation for the REST web service. Go to the proxyminion_rest_example folder.
-
Run the following command to start the REST web service.
python rest.py --address <your ip address> --port 8000
-
Open a browser and load [role="bare"]http://«your ip address»:8000. This will show the default page with services and packages as shown in the screenshot below.

现在,我们已经配置了 REST 网络服务,并且它将检查如何配置盐代理来查询 REST 网络服务并控制系统。
Now, we have configured the REST web service and it will check how to configure salt proxy to query the REST web service and control the system.
Configure Salt-Proxy
要配置盐代理,我们必须遵循以下步骤。
To configure the Salt-Proxy, we have to follow the steps given below.
-
We have to specify the master node for the salt-proxy. Edit the proxy-configuration file location, which is in/etc/salt /proxy, and enter the following code.
master: <your ip address>
-
Modify / create base pillar file in /srv/pillar/top.sls as shown in the following code block.
base:
'p8000':
- p8000
-
Add a new pillar file, p8000.sls in the /srv/pillar as shown in the code block below.
proxy:
proxytype: rest_sample
url: http://<your ip address>:8000
-
Start salt-proxy in the debug mode using the following command.
salt-proxy --proxyid = p8000 -l debug
-
Similar to the salt-minion, accept the salt-proxy key as shown below.
salt-key -y -a p8000
The following keys are going to be accepted:
Unaccepted Keys:
p8000
Key for minion p8000 accepted.
Running the Salt
现在,运行 salt 命令并调用 ping.test 函数,如下所示。
Now, run the salt command and call the ping.test function as shown below.
salt p8000 test.ping
我们可以使用 salt 运行 REST web 服务支持的任何函数,它类似于 salt-minion 。
We can run any function supported by the REST web service by using salt, which is similar to salt-minion.
例如,可以通过以下命令获取 grain 信息。
For example, the grain information can be obtained by using the following command.
salt p8000 grains.items
SaltStack - Event system
Salt 中的事件系统是一个本地的 ZeroMQ PUB 接口,用于触发 Salt 事件。以下组件会执行事件系统:
The event system in Salt is a local ZeroMQ PUB interface, which fires salt events. It is performed by the following components.
-
Event Sockets − It is used to publish events.
-
Event library − It is used to listen to events and send the events into the salt system.
Salt Master Event
Salt Master 提供了不同的事件类型,如下详细说明:
A Salt master provides different types of events, which are explained in detail below −
-
Authentication events
-
Start events
-
Key events
-
Job events
-
Runner Events
-
Presence Events
-
Cloud Events
让我们详细了解每种事件类型。
Let us go through each of the event types in detail.
Authentication Events
当 Minion 对 Master 执行身份验证检查时,将触发这些身份验证事件。事件由 salt/auth 表示。
These authentication events fire when a minion performs an authentication check with the master. It is represented by salt/auth.
Start Events
每次 Minion 连接到 Salt Master 时,都会触发开始事件,事件由 salt/minion//start 表示。
The start events fire whenever a minion connects to the Salt master and it is represented by salt/minion//start.
Key Events
当 Salt Master 在 Salt Minion 上接受和拒绝密钥时,将触发密钥事件。可以使用 salt-key 命令访问此事件。
The Key events are fired when the salt master is accepting and rejecting keys on the Salt minion. You can access this event using the salt-key command.
Job Events
每次将开始新作业时,都会触发作业事件。它由 salt/job//new 表示。其中,JID - 作业 ID,new - 新作业。
A Job event is fired whenever a new job is going to start. It is represented by salt/job//new. Here, JID - Job id new - new job
Runner Events
当 Runner 开始执行时,会触发 Runner 事件。事件由 salt/run//new 表示。
When a runner begins execution, a runner event is fired. It is represented by salt/run//new.
Presence Events
当 Minion 已连接、新建连接或断开连接时,会定期触发此事件。由 salt/presence/present 和 salt/presence/change 表示。其中,
When minions are connected or newly connected or disconnected, this event is fired on a regular interval. It is represented by – salt/presence/present and salt/presence/change. Here,
-
Present − means the Salt master is currently connected to the minions list.
-
Change − used to detect a new minion – connected or disconnected.
Cloud Events
Salt-Cloud 事件在虚拟机上触发。它不会在 Minion 上执行,除非其他事件会执行。可以使用 salt/cloud//creating 访问此事件。当 Salt Cloud 启动虚拟机执行过程时,会触发此事件。
The salt-cloud events are fired on a virtual machine. Unless other events, it is not performed on the minion. You can access it using – salt/cloud//creating. It is fired when a Salt cloud starts the virtual machine execution process.
Event Tools
现在,让我们了解事件工具和脚本。可以使用 CLI 访问事件总线。通过以下命令进行访问。
Now, let us go through the event tools and scripts. You can access the event bus using CLI. It is accessed by the following command.
salt-run state.event pretty = True
在这里,运行程序设计为从外部工具和 shell 脚本与事件总线进行交互。可通过 REST API 远程访问 Salt 的事件总线。以 – (示例 URL) 表示。
Here, the runner is designed to interact with the event bus from external tools and shell scripts. Salt’s event bus can be accessed remotely via the REST API. It is represented by – (sample URL).
curl -SsNk https://salt-api.example.com:8000/events?token = 05A3.
同样,您还可以从 Python 脚本访问事件。
Similarly, you can access events from the Python scripts as well.
SaltStack - Orchestration
总体而言, orchestration 是对系统进行自动化协调和安排。Orchestrate Runner用于在SaltStack中执行编排。
In general, orchestration is an automated coordination and arrangement of systems. Orchestrate runner is used to perform the orchestration in SaltStack.
Orchestrate Runner
Orchestrate Runner提供了 OverState (以前的系统)的所有功能。它最初被称为 state.sls Runner。该Orchestrate Runner用于将Salt状态系统概括为Salt master上下文。
he Orchestrate Runner offers all the functionality of the OverState (previous system). It is originally called as the state.sls runner. This orchestrate runner is used to generalize the Salt state system to a Salt master context.
state.sls 和 state.highstate 功能在每个Salt minion上执行,但 state.orchestrate runner在master上执行。 state.orchestrate Runner允许您将整个基础架构完全作为状态进行管理。让我们了解如何完成一个简单的执行过程。
The state.sls and the state.highstate functions are executed on each Salt minion, but the state.orchestrate runner is executed on the master. The state.orchestrate runner allows you to manage your entire infrastructure as state fully. Let us understand how to go through a simple execution process.
Simple Execution
编排运行器命令与 state.sls 函数相同,但是可以使用“salt-run”而不是salt来执行该命令。
The Orchestrate Runner command is same as the state.sls function, but you can execute it with the “salt-run” instead of salt.
假设您在 /srv/salt/orch/samples.sls 处有一个 sample.sls 文件。将以下代码添加到该文件中。
Assume that you have a sample.sls file located at /srv/salt/orch/samples.sls. Add the following code in that file.
sample.sls
sample.sls
install_nginx:
salt.state:
- tgt: 'web*'
- sls:
- nginx
以下命令用于在主控程序上运行,它将应用该文件中定义的状态。
The following command is used to run on the master and it will apply the states defined in that file.
salt-run state.orchestrate orch.sample
它将生成以下 output −
It will produce the following output −
saltmaster.local_master:
----------
ID: install_nginx
Function: salt.state
Result: True
Comment: States ran successfully.
Started: 11:54:56.308078
Duration: 63.401 ms
Changes:
Summary for saltmaster.local_master
------------
Succeeded: 1
Failed: 0
------------
Total states run: 1
Total run time: 63.401 ms
root@saltmaster:/home/vagrant#
这里,根据当前版本,运行程序函数更名为 state.orchestrate 。这将有助于避免与 state.sls 执行函数混淆,但必须使用 state.sls 的先前版本。
Here, according to the Current Version, the runner function was renamed to state.orchestrate. This will be helpful to avoid confusion with the state.sls execution function, but the previous versions of state.sls must be used.
Execute Function
要执行函数,您应使用 salt.function 。考虑一个位于 /srv/salt/orch/data.sls 的文件 data.sls 。现在,在该文件中添加以下更改。
To execute a function, you should use the salt.function. Consider a file data.sls located at /srv/salt/orch/data.sls. Now, add the following changes in that file.
data.sls
data.sls
cmd.run:
salt.function:
- tgt: '*'
- arg:
- rm -rf /tmp/data
以下命令用于执行 Salt 函数。
The following command is used to execute the Salt function.
root@saltmaster:/home/vagrant# salt-run state.orchestrate orch.data
它将生成以下 output −
It will produce the following output −
saltmaster.local_master:
----------
ID: cmd.run
Function: salt.function
Result: True
Comment: Function ran successfully. Function cmd.run ran on minion1, minion2.
Started: 12:14:54.791635
Duration: 234.615 ms
Changes:
minion1:
minion2:
Summary for saltmaster.local_master
------------
Succeeded: 1 (changed = 1)
Failed: 0
------------
Total states run: 1
Total run time: 234.615 ms
SaltStack - Salt Package Manager
Salt 配方使用包管理器打包并分发到 Salt 主控。这个概念受到 RPM 、 Yum 和 Pacman 的影响。配方使用 Salt 状态、支柱、文件模板和其他文件,然后将其打包到一个文件中。
Salt formulas are packaged and distributed to Salt masters using the package manager. This concept was influenced from RPM, Yum and Pacman packaging systems. Salt state, pillar, file templates and other files are used by the formula and then packaged into a single file.
在创建配方包后,将其复制到存储库系统以使其可供 Salt 主控使用。在转到包管理器之前,让我们先了解如何使用 Salt 基本命令安装“nginx”包。
After a formula package is created, it is copied to the Repository System to make it to use for Salt masters. Before moving to the package manager, let us have a look at how to install an “nginx” package using the Salt basic command.
以下语法用于安装“nginx”包。
The following syntax is used to install a “nginx” package.
root@saltmaster:/home/vagrant# salt '*' pkg.install nginx
这里, pkg.install nginx 命令用于安装一个包。在执行后,您将看到以下响应。
Here, the pkg.install nginx command is used to install a package. After execution, you will see the following response.
它将生成以下 output −
It will produce the following output −
minion2:
----------
httpd:
----------
new:
1
old:
httpd-cgi:
----------
new:
1
old:
libxslt1.1:
----------
new:
1.1.28-2build1
old:
nginx:
----------
new:
1.4.6-1ubuntu3.7
old:
nginx-common:
----------
new:
1.4.6-1ubuntu3.7
old:
nginx-core:
----------
new:
1.4.6-1ubuntu3.7
old:
minion1:
----------
httpd:
----------
new:
1
old:
httpd-cgi:
----------
new:
1
old:
libxslt1.1:
----------
new:
1.1.28-2build1
old:
nginx:
----------
new:
1.4.6-1ubuntu3.7
old:
nginx-common:
----------
new:
1.4.6-1ubuntu3.7
old:
nginx-core:
----------
new:
1.4.6-1ubuntu3.7
old:
现在,您已经安装了一个包。要启动该包的服务,请使用下面给出的命令。
Now, you have installed a package. To start the services for that package, use the command given below.
root@saltmaster:/home/vagrant# salt '*' service.start nginx
运行此命令后,结果如下所示的代码块所示。
After running this command, the result looks as shown in the code block below.
minion1:
True
minion2:
True
因此,我们使用基本命令安装并启动了“nginx”包的服务。现在让我们讨论如何在 Salt 包管理器中构建和安装包。
Therefore, we have installed and started the services for the “nginx” package using the basic command. Let us now discuss how to build and install packages in the Salt package manager.
Building Packages
可以在你可以安装 Salt 的任何系统上构建包。有三种类型的包,如下所示。
Packages can be built on any system where you can install Salt. There are three type of packages and they are follows.
-
Formula
-
Reactor
-
Conf
现在让我们了解如何使用 Fomula 文件构建包。
Let us now understand how to build packages using the Fomula File.
Formula File
默认情况下,包中的大多数文件都位于 – /srv/spm/salt/ 目录中,但支柱文件可以放置在 – /srv/spm/pillar/ 目录中。配方文件描述了这个包。
Most files from the package are located at the – /srv/spm/salt/ directory by default, but the pillar file can be placed in the – /srv/spm/pillar/ directory. The Formula file describes the package.
Example
name: apache
os: RedHat
os_family: RedHat
version: 201607
release: 2
summary: Formula for installing Apache
description: Formula for installing Apache
在此,
Here,
-
Name − The name of the package. Here, the package name is apache.
-
os − It is used to know which operating systems can support this package.
-
os_family − It is used to know which operating system families can support this package.
-
Version − The version of the package. It is specified in an YYYYMM format.
-
Release − This field refers primarily to a release of a version.
-
Summary − Short lines description of the package.
-
Description − A more detailed description of the package.
REACTOR
反应器文件驻留在 /srv/spm/reactor/ 目录中。
The reactor files resides in the /srv/spm/reactor/ directory.
CONF
此类包中的文件是 Salt 的配置文件,这些文件通常存在于 /etc/salt/ 目录中。其他应用程序的配置文件可以使用 Salt 状态处理,并且应该使用 Salt 状态处理(使用公式类型的包)。
The files in this type of a package are configuration files for Salt, which normally live in the /etc/salt/ directory. Configuration files for packages other than Salt can and should be handled with a Salt State (using a formula type of package).
让我们继续执行以下步骤来构建一个软件包。
Let us continue with the following steps to build a package.
-
Create a FORMULA file and place it in the root of the package folder.
-
Assemble the formula files in a folder on the build system.
-
Run spm build. The package is built and placed in the /srv/spm_build folder. The following command is used to build a package.
spm build /path/to/salt-packages-source/formula
-
Now, copy the .spm file to a folder on the repository system.
-
You can share the srv/spm_build folder on the network, or copy the files to your FTP or the Webserver.
-
Generate repo metadata using the following command.
spm create_repo /srv/spm_build
Installing Packages
本部分解释了如何安装 Salt 软件包管理器软件包。
This section explains about installing Salt package manager packages.
Configure Remote Repositories
要配置远程存储库,Salt Master 需要通过配置过程来了解存储库所在位置。
To configure remote repositories, the Salt Master needs to know where the repository is through a configuration process.
文件位于 /etc/salt/spm.repos.d/spm.repo 目录中。
Files are in the /etc/salt/spm.repos.d/spm.repo directory.
Example
file_repository:
url: https://spm.example.com/
此处,该文件包含存储库的名称和指向存储库的链接。您还可以使用 http、https、ftp 或文件路径。要使用文件路径,您可以使用以下 URL 访问它: [role="bare"] [role="bare"]file:///srv/spm_build 。
Here, the file contains the name of the repository and the link to the repository. You can also use http, https, ftp, or the file path. To use file path, you can access it using the URL: [role="bare"]file:///srv/spm_build.
Update Metadata
在 Salt master 上配置存储库后,使用以下命令下载存储库元数据。
After the repository is configured on the Salt master, repository metadata is downloaded using the command below.
spm update_repo
Update File Roots
SPM 软件包位于 srv/spm/salt 目录中。将以下路径添加到 Salt master 上的文件根目录中,
The SPM packages are located in the srv/spm/salt directory. Add the following path to the file roots on the Salt master,
file_roots:
base:
1. /srv/salt
2. /srv/spm/salt
现在,重新启动 salt master。
Now, restart the salt master.
SaltStack - Python API
Salt 向其所有命令提供编程访问。Salt 为 Salt 系统的每个部分提供不同的模块。让我们在此章节中学习 python API 基础知识以及如何在 Salt 系统中运行基本 Salt 命令。
Salt provides programmatic access to all of its commands. Salt provides different modules for every section of the Salt system. Let us learn the basics of the python API and about how to run the basic salt commands in this chapter.
Configuration
salt.config 模块用于访问 Salt 配置详细信息。
The salt.config module is used to access Salt configuration details.
import salt.config
opts = salt.config.client_config('/etc/salt/master')
此处, client_config 读取 salt 配置文件并以字典的形式返回配置详细信息。
Here, the client_config reads the salt configuration file and returns the configuration details as dictionary.
Loader
salt.loader 模块用于加载 Salt 中的每个模块,例如 grains、minions 等。
The salt.loader module is used to load each modules in Salt such as grains, minions, etc.
import salt.loader
opts = salt.config.minion_config('/etc/salt/minion')
grains = salt.loader.grains(opts)
此处, grains 读取 Salt 系统中的 grains 详细信息并将其返回。
Here, grains reads the details of the grains in the Salt system and returns it.
Client Module
salt.client 模块用于以编程方式执行 salt、salt-call 和 salt-SSH 命令。
The salt.client module is used to execute salt, salt-call and the salt-SSH commands programmatically.
最重要的 python 类如下−
The most important python classes are as follows −
-
salt.client.LocalClient
-
salt.client.Caller
-
salt.client.ssh.client.SSHClient
大多数客户端模块提供的主要函数是 cmd 。此函数包装 CLI 选项并执行它,类似于命令行并返回结果作为 python 数据结构。
The main function provided by most of the client module is cmd. This function wraps the CLI options and executes it, which is similar to the command line and returns the results as python data structures.
LocalClient
LocalClient 用于将命令从 master 发送到 salt minion,并将结果返回给 master。
The LocalClient is used to send commands from the master to the salt minions and return the results to the master.
import salt.client
local = salt.client.LocalClient()
local.cmd('*', 'test.ping')
它将生成以下 output −
It will produce the following output −
{'minion1': True, 'minion2': True }
Caller
Caller 用于以编程方式运行 salt-call 并返回结果。
The Caller is used to run salt-call programmatically and return the results.
import salt.client
caller = salt.client.Caller()
caller.cmd('test.ping')
它将生成以下 output −
It will produce the following output −
True
SSHClient
SSHCient 用于以编程方式运行 salt-ssh 并返回结果。
The SSHCient is used to run the salt-ssh programmatically and return the results.
import salt.client.ssh.client
ssh = salt.client.ssh.client.SSHClient()
ssh.cmd('*', 'test.ping')
它将生成以下 output −
It will produce the following output −
{'minion1': True, 'minion2': True }
CloudClient
salt.cloud 模块用于以编程方式执行 salt-cloud 命令。
The salt.cloud module is used to execute the salt-cloud commands programmatically.
client = salt.cloud.CloudClient(path = '/etc/salt/cloud')
Cloud 模块提供创建 VM (create)、销毁 VM (destroy)、列出云供应商提供的映像 (list_images)、列出云供应商的位置 (list_locations)、列出云供应商的机器大小 (list_sizes) 等函数。
Cloud module provides functions to create VMs (create), to destroy VMs (destroy), list images provided by a cloud provider (list_images), list locations of a cloud provider (list_locations), list machine sizes of a cloud provider (list_sizes), etc.
SaltStack - Working Example
在此操作示例中,我们将创建一个 Salt 公式,该公式将配置 apache Web 服务器以及 PHP 软件。Salt 是一个执行临时命令的好方法,但您不会真正希望持续以这种方式配置您的基础设施。通过创建一组 Salt 公式,您可以可靠地重现任何配置。
In this working example, we will create a Salt formula that will configure the apache web server along with the PHP software. Salt is a great way to execute ad-hoc commands, but you would not really want to continually configure your infrastructure this way. By creating a set of Salt formulas, you can reliably reproduce any configuration over.
Salt 公式是简单的 YAML 文本文件,并且默认驻留在 /srv/salt/ 中的 Salt 主服务器上。我们开始创建一个 Salt 公式以便同时安装 Apache Web Server 和 PHP。
Salt Formulas are simple YAML text files and by default reside on your Salt Master in /srv/salt/*. Let us start by creating a Salt Formula to install the Apache web server and PHP at the same time.
在 /srv/salt/ 目录下创建一个名为“websetup.sls”的文件并添加下面的代码。
Create a file named “websetup.sls” under /srv/salt/ directory and add the following code.
websetup.sls
websetup:
pkg:
- installed
- pkgs:
- apache2
- php5
- php5-mysql
在这个示例中,请注意“- pkgs:”参数。“- pkgs:”下面列表中的每一项都会被一起传递给操作系统程序包管理器以一起安装。当您有很多要安装的程序包列表时,这是安装它们最有效的方法。
In this example, notice the “- pkgs:” argument. Each item in the list below “- pkgs:” will be passed together to OS’s package manager to be installed together. Whenever you have a large list of packages to install this is the most efficient way to install them.
使用下面的命令将这个公式应用到 Salt 主服务器。
Apply this Formula to Salt master using the following command.
root@saltmaster:/home/vagrant# salt 'minion2' state.sls websetup
现在,您将看到以下 output −
Now, you will see the following output −
minion2:
----------
ID: websetup
Function: pkg.installed
Result: True
Comment: 3 targeted packages were installed/updated.
Started: 01:50:53.978396
Duration: 86738.132 ms
Changes:
----------
apache2:
----------
new:
2.4.7-1ubuntu4.13
old:
apache2-api-20120211:
----------
new:
1
old:
apache2-bin:
----------
new:
2.4.7-1ubuntu4.13
old:
apache2-data:
----------
new:
2.4.7-1ubuntu4.13
old:
libapache2-mod-php5:
----------
new:
5.5.9+dfsg-1ubuntu4.21
old:
libapr1:
----------
new:
1.5.0-1
old:
libaprutil1:
----------
new:
1.5.3-1
old:
libaprutil1-dbd-sqlite3:
----------
new:
1.5.3-1
old:
libaprutil1-ldap:
----------
new:
1.5.3-1
old:
php5:
----------
new:
5.5.9+dfsg-1ubuntu4.21
old:
php5-cli:
----------
new:
5.5.9+dfsg-1ubuntu4.21
old:
php5-common:
----------
new:
5.5.9+dfsg-1ubuntu4.21
old:
php5-json:
----------
new:
1.3.2-2build1
old:
php5-mhash:
----------
new:
1
old:
php5-mysql:
----------
new:
5.5.9+dfsg-1ubuntu4.21
old:
php5-readline:
----------
new:
5.5.9+dfsg-1ubuntu4.21
old:
phpapi-20121212:
----------
new:
1
old:
ssl-cert:
----------
new:
1.0.33
old:
Summary for minion2
------------
Succeeded: 1 (changed = 1)
Failed: 0
------------
Total states run: 1
Total run time: 86.738 s
现在,您已在 minion2 中安装了程序包。
Now, you have installed the packages in minion2.
Highstate
“highstate” 是 Salt 用以确定哪些 Salt 公式应该被应用到某个 minions 的一种方法。使用下面的命令执行一个“highstate”。
A “highstate” is a way for Salt to determine which of the Salt Formulas should be applied to a certain minion. Execute a “highstate” using the following command.
root@saltmaster:/home/vagrant# salt <targets> state.highstate
top.sls
正如前面提到的,当 minions 请求执行一个“highstate”时,它向 Salt 主服务器请求 top.sls 并搜索它可以匹配的公式。默认情况下,该文件位于 /srv/salt/top.sls。我们把我们的公式添加到 top.sls 文件中并将 minion2 作为目标。
When the minion request to execute a highstate, as mentioned before, the minion requests the top.sls from the Salt master and searches for formulas that it matches. By default, this file is located at /srv/salt/top.sls. Let us add our formula to the top.sls file and set minion2 as target.
base:
'*':
- common
'minion2’:
- websetup
现在,执行 highstate 以将 minion2 作为目标,如下所示。
Now, execute the highstate targeting minion2 as shown below.
root@saltmaster:/home/vagrant# salt 'minion2' state.highstate
应用该文件后,您会看到以下 output −
After applying this, you could see the following output −
minion2:
----------
ID: common_packages
Function: pkg.installed
Result: True
Comment: All specified packages are already installed
Started: 01:55:17.998824
Duration: 461.615 ms
Changes:
Summary for minion2
------------
Succeeded: 1
Failed: 0
------------
Total states run: 1
Total run time: 461.615 ms
现在,Apache Web Server 和 PHP 已安装在 minion2 中。通过这种方式,我们必须使用 top.sls 和 highstate 同时对 minions 定位目标,然后在最少的工作量和最大的灵活性下安装所需的软件。
Now, Apache web server and PHP is installed in the minion2. In this way, we have to target minions using both top.sls and highstate and install the required software with minimal work and maximum flexibility.