salt 入门讲解

saltstack 主要功能:

远程执行命令,比如看一下所有机器操作系统的version。

配置,配置apache,mysql等等都可以用它

软件安装

服务启动,重启

信息收集归档

master和minion各自干了哪些活:

master:

存放所有minion的公钥

监听minion

发送命令给minion

存放一些为minion准备的配置文件,如state

存放一些为minion准备的files和数据,如apache2.cnf,pillar

minion:

连接master

监听master发送的commands

从master下载state并且执行state

可以执行在minion上执行state,用salt-call

master and minion 有两种方式push and pull, 下面讲解一下master and minion install及pull方式的例子, here master and minion install 在同一台机器, install system is centos 7.

1.1 Update the system

Use the sudo user to log into the SaltStack master server, then update the system to the latest stable status:

sudo yum update -y && sudo reboot

After the reboot completes, use the same sudo user to log in.

1.2 Install and configure the salt-master program

Use the SaltStack official YUM repo to install the latest salt-master program:

sudo yum clean expire-cache

sudo yum install salt-master

After the installation finishes, modify the configuration file as below:

sudo vi /etc/salt/master

Find:

#interface: 0.0.0.0

Replace the line with:  master ip value

interface: 10.29.76.235

Find:

#hash_type: md5

Replace the line with:

hash_type: sha256

Save and quit:

:wq

Start and enable the salt-master service:

sudo systemctl start salt-master.service

sudo systemctl enable salt-master.service

Step 2: Operations on the SaltStack agent server

2.1 Update the system

Use the sudo user to log in the SaltStack agent server. Again, update the system to the latest stable status:

sudo yum update -y && sudo reboot

After the reboot, use the same sudo user to log in.

2.2 Install and configure the salt-minion program

Use the SaltStack official YUM repo to install the latest salt-minion program:

sudo yum clean expire-cache

sudo yum install salt-minion

After the installation, modify the configuration file as below:

sudo vi /etc/salt/minion

Find:

#master: salt

Replace the line with: master ip value

master: 10.29.76.235

Find:

#hash_type: sha256

Replace the line with:

hash_type: sha256

Save and quit:

:wq

Start and enable the salt-minion service:

sudo systemctl start salt-minion.service

sudo systemctl enable salt-minion.service

After starting up, the salt-minion service will send off a signal to find the SaltStack server.

If you have more SaltStack agent servers, you need to setup them in the same fashion.

Step 3: Test your setup on the SaltStack master server

Return to the SSH connection to the SaltStack master server, input the following command to show all available agents:

sudo salt-key -L

If everything was successful, you will see the agent server "minion1" listed in the "Unaccepted Keys" segment.

!119 $ sudo salt-key -L

Accepted Keys:

ip-10-29-76-235.ec2.internal

Denied Keys:

Unaccepted Keys:

Rejected Keys:

Accept "minion hostname" using this command :

salt-key --accept=ip-10-29-76-235.ec2.internal

Or accept all of the agent servers:

salt-key -A

Finally, you can test your setup using the example commands below:

Example 1:

sudo salt  ip-10-29-76-235.ec2.internal test.ping

The output show:

sudo salt  ip-10-29-76-235.ec2.internal test.ping

ip-10-29-76-235.ec2.internal:

    True

Example 2:

sudo salt ip-10-29-76-235.ec2.internal cmd.run pwd

The output show:

sudo salt ip-10-29-76-235.ec2.internal cmd.run pwd

ip-10-29-76-235.ec2.internal:

    /root

That's it. You can learn more about SaltStack on its official website. Enjoy it!

管理端(master)常用相关命令

 1.1 salt     #主要管理命令

   命令格式:salt [options]  <target> [arguments]

    例:salt ‘*’ test.ping

 1.2 salt-key #证书管理

    # salt-key –L           #查看所有minion-key

    # salt-key –a  <keys-name>   #接受某个minion-key

    # salt-key –d  <keys-name>   #删除某个minion-key

    # salt-key –A           #接受所有的minion-key

    # salt-key –D           #删除所有的minion-key

 1.3 salt-run #管理minion

    # salt-run manage.up           #显示当前活着的minion

    # salt-run manage.down           #显示未存活的minion

    # salt-run manage.status         #显示当前up和down 的minion   

    # salt-run manage.downremovekeys-True   #显示未存活的minion,并将其移除

 1.4 salt-cp #将master文件复制到minion,不支持复制目录

   命令格式:salt-cp [options]<target> SRC DST

   例:salt-cp '*'/root/test.sh  /root/test.sh

 1.5 salt-ssh   

   #通过ssh连接被管理端,被管理端不用安装minion,管理端也不用安装master,salt-ssh是一个独立的包,安装后即可使用saltstack大部分功能,没有通讯机制ZeroMQ,命令执行速度会下降。一般没有客户端没有安装minion时候才考虑先用salt-ssh批量安装minion。

   # apt-get install salt-ssh sshpass   #salt-ssh用的sshpass进行密码交互,必须要安装

   1.5.1 salt-ssh常用参数

 -r,-raw-shell :执行shell命令  

    --key-deploy   :配置keys

    -i,-ignore-host-keys  :当ssh连接时,忽略keys

     -passwd      :指定默认密码

     -roster-file   :指定roster文件

   1.5.2 salt-ssh使用

    1.5.2.1 sat-ssh通过调用roster配置文件实现,所以先定义roster,让salt-ssh生效,就可以执行操作了

    # vi /etc/salt/roster

    db:

      host: 192.168.18.212

      user: root

      passwd: 123456

      port: 22

      timeout: 10

    1.5.2.1 测试

    # salt-ssh 'db' test.ping

    db:

        True

    1.5.2.3 执行shell命令及salt本身的模块

    #第一次运行时会提示是否接受秘钥,如果不想再提示可以加入—key-deploy参数

    # salt-ssh 'db' -r 'uptime'     

    # salt-ssh 'db' disk.usage          #调用salt本身的模块

    # salt-ssh 'db' grains.itemcpu_model   #获取grains信息

2、Pillar

 上节讲过Salt State,Salt状态系统的核心SLS,也可叫做配置管理,SLS描述了系统的目标状态,由简单的格式来包含这些数据。

 Pillar是Salt最重要的系统之一,可用于提供开发接口,用于在master端定义数据,然后再minion中使用,一般传输敏感的数据,例如ssh key,加密证书等。

 pillar和states建立方式类似,由sls文件组成,有一个入口文件top.sls,通过这个文件关联其他sls文件,默认路径在/srv/pillar,可通过/etc/salt/master里面pillar_roots:指定位置。

 pillar到底什么作用呢?那么下面介绍一个简单的例子,你就明白了。

 用zabbix监控新上架的服务器(10台),需要将zabbix_agentd.conf分发到被监控主机,这个文件中hostname的ip每台都不同,我们不可能写10分配置文件吧!那么如何让hostname在分发的时候就根据被监控主机IP,修改成自己的呢?这时就用到渲染了,默认渲染器是jinja,支持for in循环判断,格式是{%...%}{% end* %},这样一来salt会先让jinja渲染,然后交给yaml处理。

 2.1 创建pillar目录和top.sls文件

 # mkdir /srv/pillar

 # vi /srv/pillar/top.sls

base:

  '*':

    - ip

 2.2 先通过pillar获取minion主机IP

 # vi /srv/pillar/ip.sls

 ip: {{ grains['ipv4'][1] }}

#刷新pillar数据到minion

!132 $sudo  salt "*" saltutil.refresh_pillar

ip-10-29-76-235.ec2.internal:

    True

#写完后,执行sls命令,可以看到已经获取到IP

sudo salt '*' pillar.item ip

ip-10-29-76-235.ec2.internal:

    ----------

    ip:

        127.0.0.1

 2.3 随后写个sate文件,将文件分发到minion上

 # mkdir /srv/salt/zabbix

 # vi /srv/salt/zabbix/agentd_conf.sls

zabbix:

  file.managed:

    - source: salt://zabbix/zabbix_agentd.conf

    - name: /usr/local/zabbix/conf/zabbix_agentd.conf

    - template: jinja

    - defaults:

      ip: {{ pillar['ip'] }}

 2.4 修改zabbix_agentd.conf要渲染的IP

 # vi /srv/salt/zabbix/zabbix_agentd.conf

 LogFile=/tmp/zabbix_agentd.log

 Server=192.168.18.214

 ServerActive=127.0.0.1

 Hostname={{ ip }}

2.5执行单sls命令,不用将sls文件关联到top.sls文件                         

!129 $ sudo salt '*' state.sls zabbix.agentd_conf

ip-10-29-76-235.ec2.internal:

----------

          ID: zabbix

    Function: file.managed

        Name: /usr/local/zabbix/conf/zabbix_agentd.conf

      Result: True

     Comment: File /usr/local/zabbix/conf/zabbix_agentd.conf is in the correct state

     Started: 05:38:03.791391

    Duration: 35.537 ms

     Changes:   

Summary for ip-10-29-76-235.ec2.internal

------------

Succeeded: 1

Failed:    0

------------

Total states run:    1

Total run time:  35.537 ms

 #这时再通过命令查看,已经更新成功

!131 $ sudo salt '*' cmd.run 'cat /usr/local/zabbix/conf/zabbix_agentd.conf'

ip-10-29-76-235.ec2.internal:

    LogFile=/tmp/zabbix_agentd.log

    Server=192.168.18.214

    ServerActive=127.0.0.1

    Hostname=127.0.0.1

pillar相关命令:

#刷新pillar数据到minion

# salt "*" saltutil.refresh_pillar

#查看所有pillar信息

# salt "*" pillar.items

#查看某个pillar信息

# salt "*" pillar.item ip

既然grains与pillar类似,就说下区别:

1.grains是minion每次加载时获取本地系统信息数据,是静态的,固定的,而pillar是动态加载数据,随时变化的,比grains更灵活。

2.grains数据存储在minion本地,pillar存储在master。

salt-minion aws 安装

脚本安装系统是Centos.

testminion.sh

#!/bin/bash

systemctl stop salt-minion

sleep 5


echo "master: 10.29.76.235" >> /etc/salt/minion.d/master.conf

echo `hostname` > /etc/salt/minion_id

echo "environment: test" >> /etc/salt/minion.d/environment.conf

echo "pillarenv: test" >> /etc/salt/minion.d/environment.conf


echo "hostname: `hostname`" >> /etc/salt/grains

echo "env: dev" >> /etc/salt/grains

echo "project: test" >> /etc/salt/grains

echo "app: test" >> /etc/salt/grains

echo "service: test" >> /etc/salt/grains


echo "startup_states: highstate" >> /etc/salt/minion.d/startup.conf

yum remove -y salt

yum remove -y salt-minion

yum clean all

yum install -y salt-minion

sleep 5

systemctl start salt-minion


pull mechanism Example:

First step:

Minion machine:

Run this script testminion.sh above.

sudo sh testminion.sh

!116 $ sudo cat /etc/salt/minion.d/master.conf

master: 10.29.76.235

!121 $ sudo cat /etc/salt/minion_id

ip-10-29-76-235.ec2.internal


!122 $sudo  cat /etc/salt/minion.d/environment.conf

environment: test

pillarenv: test


!123 $ sudo cat /etc/salt/grains

hostname: ip-10-29-76-235.ec2.internal

env: dev

project: test

app: test

service: test

!124 $ sudo cat /etc/salt/minion.d/startup.conf

startup_states: highstate

master machine:

sudo yum install salt-master


Notes: please pay attention to remove blank line when you copy content into machine.

$  sudo mkdir -p /srv/pillar

!117 $ sudo vim /srv/pillar/top.sls

test:

  'G@service:test':

    - test

解析:

test:    //test environment

  'G@service:test':   //G stands for grain, service name equals test

    - test    //   call /srv/pillar/test.sls

test pillar value:  ()

!118 $ sudo vim /srv/pillar/test.sls

version:

   dev: 1.11

   stg: 1.12

test_env:

  default: development

  dev: development

  stg: staging


$  sudo mkdir -p /srv/salt

!119 $ sudo vim /srv/salt/top.sls

test:

  'G@service:test':

    - test.test-service-tar


$   sudo mkdir -p /srv/salt/test/

!120 $ sudo vim /srv/salt/test/test-service-tar.sls

{% set NAME = "test-service" %}

{% set test_env = salt['pillar.get']('test_env:' ~ grains['env'],  default=salt['pillar.get']('test_env:default'))  %}

{% set version = salt['pillar.get']('version:' ~ grains['env'],  default=salt['pillar.get']('version:default')) %}

{% if version and test_env  %}

create_download_path: 

  file.directory:

    - name: /home/centos/{{ NAME }}-releases/

    - makedirs: True

    - user: centos

    - group: centos


{% else %}

deploy_tar_package:

  cmd.run:

    - name: echo "test no right pillar parameters!!! " && exit 1

{% endif %}


sudo vim /etc/salt/master

# The address of the interface to bind to:interface: 10.29.76.235

interface: 10.29.76.235

# The file server works on environments passed to the master, each environment# can have multiple root directories, the subdirectories in the multiple file# roots cannot match, otherwise the downloaded files will not be able to be# reliably ensured. A base environment is required to house the top file. 


#####      File Server settings      #####

##########################################

# Salt runs a lightweight file server written in zeromq to deliver files to

# minions. This file server is built into the master daemon and does not

# require a dedicated port.

# The file server works on environments passed to the master, each environment

# can have multiple root directories, the subdirectories in the multiple file

# roots cannot match, otherwise the downloaded files will not be able to be

# reliably ensured. A base environment is required to house the top file.

# Example:

file_roots:

  base:

    - /srv/salt/

  test:

    - /srv/salt/

  dev:

    - /srv/salt/dev/services

    - /srv/salt/dev/states

# Prior to changing this value, the master should be stopped and all Salt

# caches should be cleared.

hash_type: sha256

#####        Pillar settings        #####

##########################################

# Salt Pillars allow for the building of global data that can be made selectively

# available to different minions based on minion grain filtering. The Salt

# Pillar is laid out in the same fashion as the file server, with environments,

# a top file and sls files. However, pillar data does not need to be in the

# highstate format, and is generally just key/value pairs.

pillar_roots:

  base:

    - /srv/pillar

  test:

    - /srv/pillar

start saltmaster

sudo systemctl start salt-master.service

sudo systemctl enable salt-master.service


Run accept minion key command

sudo salt-key --accept=ip-10-29-67-171.ec2.internal

sudo salt-key -L

Accepted Keys:

ip-10-29-67-171.ec2.internal

Denied Keys:

Unaccepted Keys:

Rejected Keys:

Run refresh pillar command on master machine

!126 $sudo  salt "*" saltutil.refresh_pillar

ip-10-29-76-235.ec2.internal:

    True


Run pull command on minion machine

centos@ip-10-29-76-235.ec2.internal:~ · 10:17 AM Fri Jan 17 · 

!127 $ sudo salt-call state.highstate

local:

----------

          ID: create_download_path

    Function: file.directory

        Name: /home/centos/test-service-releases/

      Result: True

     Comment: Directory /home/centos/test-service-releases is in the correct state

              Directory /home/centos/test-service-releases updated

     Started: 10:18:36.612266

    Duration: 5.199 ms

     Changes:   

Summary for local

------------

Succeeded: 1

Failed:    0

------------

Total states run:    1

Total run time:  5.199 ms


Reference

granis configure

推荐阅读更多精彩内容