學習saltstack (六)

Slatstack 介紹

官網:https://saltstack.com/php

官方源:http://repo.saltstack.com/  (介紹各操做系統安裝方法)html

centos 6源node

?
1
yum install https: //repo .saltstack.com /yum/redhat/salt-repo-latest-1 .el6.noarch.rpm

centos 7 源 python

?
1
yum install https: //repo .saltstack.com /yum/redhat/salt-repo-latest-1 .el7.noarch.rpm

http://repo.saltstack.com/yum/redhat/7/x86_64mysql

基於python開發,提供REST API接口linux

三大功能: 遠程執行、配置管理(狀態)、雲管理nginx

其它:Puppet(ruby)、ansible(python)c++

四種運行方式:Local、Minion/Master(C/S)、Syndic(代理,相似zabbix proxy)、Salt SSHgit

 

快速安裝

 - 安裝web

服務端

?
1
yum install salt-master salt-minion -y

客戶端

?
1
yum install salt-minion -y

啓動服務端

?
1
systemctl start salt-master

配置客戶端

?
1
2
3
vim /etc/salt/minion
master: 192.168.137.11  # 配置master地址
id :   # 每臺主機的惟一標識,不配置默認爲主機名

啓動客戶端

?
1
systemctl start salt-minion

啓動後/etc/salt下生成minion_id文件,默認爲主機名

若是修改id,須要刪除minion_id

 

 - master和minion啓動後pki介紹

第一次啓動minion在/etc/salt下生成pki文件目錄

包含minion的公鑰minion.pub和私鑰minion.pem

第一次啓動master在/etc/salt下生成pki文件目錄

包含master的公鑰master.pub和私鑰master.pem

linux-node1.example.com和linux-node2.example.com爲minion的公鑰,名稱爲id名

minions_pre爲預認證目錄

 

 - 認證

?
1
salt-key

Accepted Keys 已贊成的key

Denied Keys 拒絕的key

Unaccepted Keys 未認證的key

?
1
salt-key -a linux-node1.example.com

指定linux-node1.example.com這臺minion被信任

?
1
salt-key -a linux*  # 通配符

說明:-a :accept ,-A:accept-all,-d:delete,-D:delete-all

兩臺minion已認證成功,此時再次查看master pki文件目錄,minion的公鑰文件放入了minions目錄下

再次查看minion pki文件目錄,存在minion_master.pub公鑰文件

 

 - 遠程執行

語法: 命令 目標 模塊.方法 方法參數

檢查全部主機狀態

?
1
salt '*' test . ping

檢查指定主機狀態

?
1
salt "linux-node2.example.com" test . ping

指定主機,遠程執行shell命令

?
1
salt "linux-node2.example.com" cmd.run "ls -lrt /root"

重啓全部主機的zabbix agent

?
1
salt "*" cmd.run "systemctl restart zabbix-agent"

 

- 狀態模塊

state 寫一個描述文件。格式:YAML ,後綴:.sls

YAML介紹(重要)

YAML是"YAML Ain't a Markup Language"(YAML不是一種置標語言)的遞歸縮寫。(能夠查看百度百科介紹)

格式:數據結構能夠用相似大綱的縮排方式呈現,結構經過縮進來表示,連續的項目經過減號「-」來表示,map結構裏面的key/value對用冒號「:」來分隔。

樣例以下:

salt管理理解YAML介紹 https://docs.saltstack.com/en/latest/topics/yaml/index.html

salt YAML三個規則:

1)縮進,須要用2個空格,不能使用Tab鍵;

2)冒號,冒號和縮進共用、鍵值對(中間有空格)

3)短橫線, 於後面的值有空格

 

- master配置

?
1
2
vim /etc/salt/master
file_roots  # 定義base、測試、灰度、生產環境配置文件路徑,base名稱不能改

重啓master

systemctl restart salt-master

建立配置文件目錄

?
1
2
cd /srv
mkdir salt

 

 - sls文件建立

apache.sls,放入到/srv/salt/web目錄下

?
1
2
3
4
5
6
7
8
9
10
apache- install :   # 自定義的id,名稱
   pkg.installed:  # 狀態模塊,salt自帶的, 模塊.方法
     - names:      # 參數
       - httpd
       - httpd-devel
 
apache-service:      # 自定義的id,名稱
   service.running:   # 狀態模塊,salt自帶的, 模塊.方法
     - name: httpd     # 參數
     - enable : True

執行這個文件

?
1
salt "*" state.sls web.apache

執行流程:

1)master將這個文件發送至minion

2)minion放在/var/cache/salt/minion目錄下

3)minion根據這個文件從上往下執行

執行結果

  1 linux-node2.example.com:
  2 ----------
  3           ID: apache-install
  4     Function: pkg.installed
  5         Name: httpd
  6       Result: True
  7      Comment: The following packages were installed/updated: httpd
  8      Started: 13:12:23.142622
  9     Duration: 103093.75 ms
 10      Changes:   
 11               ----------
 12               apr:
 13                   ----------
 14                   new:
 15                       1.4.8-3.el7
 16                   old:
 17               apr-util:
 18                   ----------
 19                   new:
 20                       1.5.2-6.el7
 21                   old:
 22               httpd:
 23                   ----------
 24                   new:
 25                       2.4.6-40.el7.centos.4
 26                   old:
 27               httpd-tools:
 28                   ----------
 29                   new:
 30                       2.4.6-40.el7.centos.4
 31                   old:
 32               mailcap:
 33                   ----------
 34                   new:
 35                       2.1.41-2.el7
 36                   old:
 37 ----------
 38           ID: apache-install
 39     Function: pkg.installed
 40         Name: httpd-devel
 41       Result: True
 42      Comment: The following packages were installed/updated: httpd-devel
 43      Started: 13:14:06.266419
 44     Duration: 75699.845 ms
 45      Changes:   
 46               ----------
 47               apr-devel:
 48                   ----------
 49                   new:
 50                       1.4.8-3.el7
 51                   old:
 52               apr-util-devel:
 53                   ----------
 54                   new:
 55                       1.5.2-6.el7
 56                   old:
 57               cyrus-sasl-devel:
 58                   ----------
 59                   new:
 60                       2.1.26-20.el7_2
 61                   old:
 62               expat-devel:
 63                   ----------
 64                   new:
 65                       2.1.0-8.el7
 66                   old:
 67               httpd-devel:
 68                   ----------
 69                   new:
 70                       2.4.6-40.el7.centos.4
 71                   old:
 72               libdb-devel:
 73                   ----------
 74                   new:
 75                       5.3.21-19.el7
 76                   old:
 77               openldap-devel:
 78                   ----------
 79                   new:
 80                       2.4.40-9.el7_2
 81                   old:
 82 ----------
 83           ID: apache-service
 84     Function: service.running
 85         Name: httpd
 86       Result: True
 87      Comment: Service httpd has been enabled, and is running
 88      Started: 13:15:22.549732
 89     Duration: 509.773 ms
 90      Changes:   
 91               ----------
 92               httpd:
 93                   True
 94 
 95 Summary for linux-node2.example.com
 96 ------------
 97 Succeeded: 3 (changed=3)
 98 Failed:    0
 99 ------------
100 Total states run:     3
101 Total run time: 179.303 s
102 linux-node1.example.com:
103 ----------
104           ID: apache-install
105     Function: pkg.installed
106         Name: httpd
107       Result: True
108      Comment: Package httpd is already installed
109      Started: 21:12:17.773014
110     Duration: 1030.017 ms
111      Changes:   
112 ----------
113           ID: apache-install
114     Function: pkg.installed
115         Name: httpd-devel
116       Result: True
117      Comment: The following packages were installed/updated: httpd-devel
118      Started: 21:12:18.803216
119     Duration: 179505.346 ms
120      Changes:   
121               ----------
122               apr-devel:
123                   ----------
124                   new:
125                       1.4.8-3.el7
126                   old:
127               apr-util-devel:
128                   ----------
129                   new:
130                       1.5.2-6.el7
131                   old:
132               cyrus-sasl-devel:
133                   ----------
134                   new:
135                       2.1.26-20.el7_2
136                   old:
137               expat-devel:
138                   ----------
139                   new:
140                       2.1.0-8.el7
141                   old:
142               httpd-devel:
143                   ----------
144                   new:
145                       2.4.6-40.el7.centos.4
146                   old:
147               libdb-devel:
148                   ----------
149                   new:
150                       5.3.21-19.el7
151                   old:
152               openldap-devel:
153                   ----------
154                   new:
155                       2.4.40-9.el7_2
156                   old:
157 ----------
158           ID: apache-service
159     Function: service.running
160         Name: httpd
161       Result: True
162      Comment: The service httpd is already running
163      Started: 21:15:18.523234
164     Duration: 62.391 ms
165      Changes:   
166 
167 Summary for linux-node1.example.com
168 ------------
169 Succeeded: 3 (changed=1)
170 Failed:    0
171 ------------
172 Total states run:     3
173 Total run time: 180.598 s
View Code

 

- top file

默認文件名top.sls,放在base目錄下,base目錄在file_roots配置項配置

經過top.sls文件能夠實現根據不一樣的minion執行不一樣的sls文件

?
1
2
3
4
5
base:  # 固定名稱,必填
   'linux-node1.example.com' # minion id
     - web.apache  # apache.sls
   'linux-node2.example.com' :
     - web.apache

?
1
salt "*" state.highstate

上面命令執行state高級狀態,它只會執行入口文件top.sls, 根據top文件中內容執行

生產環境中不建議使用*,須要指定具體主機,先用test測試

?
1
salt "linux-node1.example.com" state.highstate test =True

測試正常後執行

?
1
salt "linux-node1.example.com" state.highstate

 

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

  • SaltStack與ZeroMQ

SaltStack底層是基於ZeroMQ進行高效的網絡通訊。

 

ZeroMQ簡介

       ØMQ (也拼寫做ZeroMQ,0MQ或ZMQ)是一個爲可伸縮的分佈式或併發應用程序設計的高性能異步消息庫。它提供一個消息隊列, 可是與面向消息的中間件不一樣,ZeroMQ的運行不須要專門的消息代理(message broker)。該庫設計成常見的套接字風格的API。可以提供進程內(inproc)、進程間(IPC)、網絡(TCP)和廣播方式的消息信道, 並支持扇出(fan-out)、發佈-訂閱(pub-sub)、任務分發(task distribution)、請求/響應(request-reply)等通訊模式。

 

 - SaltStack第一種模式:發佈與訂閱

ZeroMQ支持Publish/Subscribe,即發佈與訂閱模式,咱們常常簡稱Pub/Sub。

Salt Master運行兩個網絡服務,其中一個是ZeroMQ PUB系統,默認監聽4505端口

能夠經過修改/etc/salt/master配置文件的publish_port參數設置。

它是salt的消息發佈系統,若是查看4505端口,會發現全部的Minion鏈接到Master的4505端口,TCP狀態持續保持爲ESTABLISHED。

lsof -i:4505

 

 

 - SaltStack第一種模式:請求與響應

ZeroMQ支持Request-Reply,即請求與響應模式,咱們常常簡稱REQ/REP。

Salt Master運行的第二個網絡服務就是ZeroMQ REP系統,默認監聽4506端口,能夠經過修改/etc/salt/master配置文件的ret_port參數設置。

它是salt客戶端與服務端通訊的端口。好比說Minion執行某個命令後的返回值就是發送給Master的4506這個REP端口

若是安裝了python-setproctitle軟件包,因此咱們能夠直接看到Salt Master啓動的進程的名稱。

?
1
yum install -y python-setproctitle

重啓master和minion

?
1
2
systemctl restart salt-master
systemctl restart salt-minion

?
1
2
3
4
5
6
7
8
9
10
11
/usr/bin/salt-master -d ProcessManager  # 中心進程管理器
/usr/bin/salt-master -d _clear_old_jobs  # 清除舊的Jobs文件及更新fileserver
/usr/bin/salt-master -d Publisher       # 將任務PUB到Minion端
/usr/bin/salt-master -d EventPublisher  # Event Publisher進程
/usr/bin/salt-master -d ReqServer_ProcessManager # ReqServer進程管理器
/usr/bin/salt-master -d MWorker  # 工做進程
/usr/bin/salt-master -d MWorker  # 工做進程
/usr/bin/salt-master -d MWorker  # 工做進程
/usr/bin/salt-master -d MWorker  # 工做進程
/usr/bin/salt-master -d MWorker  # 工做進程
/usr/bin/salt-master -d MWorkerQueue # 將Ret接口(ROUTER)數據轉發到Worker(DEALER)

 

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

  • Saltstack數據系統

分爲Grains和Pillar

 

1、Grains

靜態數據,當Minion啓動的時候收集的MInion本地的相關信息。(包含操做系統版本、內核版本、CPU、內存、硬盤、設備型號等)

備註:不重啓minion,這些信息數據是不會改變的。

1)信息管理,包括資產管理;

例:

?
1
2
3
4
salt 'linux-node1*' grains. ls  # 列出ID爲linux-node1的主機,grains的全部key
salt 'linux-node1*' grains.items  # 列出主機的詳細信息,可用於資產管理
salt '*' grains.item os  # 列出全部主機的系統版本
salt '*' grains.item fqdn_ip4  # 列出全部主機的IP地址

2)用於目標選擇;(查詢具體id的主機,查詢系統版本爲centos的主機 等場景)

例:

?
1
2
salt -G 'os:Centos' test . ping  # 全部主機系統爲centos版本ping測試
salt -G 'os:Centos' cmd.run 'echo 123'  # 全部主機系統爲centos版本執行命令'echo 123'

3)配置管理中使用

自定義grains的item

方式一: 修改配置文件 vim /etc/salt/minion

重啓 systemctl restart salt-minion

經過自定義的item,能夠實現重啓全部角色爲apache的主機

?
1
2
salt '*' grains.item roles  # 獲取全部主機的roles
salt -G 'roles:apache' cmd.run 'systemctl restart httpd'  # 全部主機roles爲apache的執行命令systemctl restart httpd

方式二:(生產環境使用) 

修改配置文件 vim /etc/salt/grains,寫法

?
1
cloud: openstack

重啓 systemctl restart salt-minion

?
1
salt '*' grains.item cloud  # 獲取全部主機的cloud

修改/etc/salt/grains不重啓服務的方法,刷新命令以下(備註:方式一和方式二修改配置文件,經過此命令均可以不用重啓服務)

?
1
salt '*' saltutil.sync_grains

grains在top FILE中的使用案例

vim /srv/salt/top.sls

?
1
2
3
4
5
6
base:
   'linux-node1.example.com' :
     - web.apache
   'roles:apache' :
     - match: grain
     - web.apach

grains腳本目錄,必須是base下建立_grains目錄(如:/srv/salt/_grains)

建立一個python腳本在/srv/salt/_grains目錄下

腳本名:my_grains.py

?
1
2
3
4
5
6
7
8
9
10
11
#!/usr/bin/env python
#-*- coding: utf-8 -*-
 
def my_grains():
     # 初始化grains字典
     grains = {}
     # 設置字典中的key-value
     grains[ 'iaas' ] = 'openstack'
     grains[ 'edu' ] = 'shhnwangjian'
     # 返回字典
     return grains

經過master同步腳本文件至每臺minion

?
1
salt '*' saltutil.sync_grains

文件放在minion主機的/var/cache/salt/minion/extmods/grains目錄下

?
1
salt '*' grains.item edu  # 獲取全部主機的edu

grains優先級(item名稱相同的狀況下): 1. 系統自帶 2. grains文件寫到 3. minion配置文件寫的 4. 本身寫的腳本

 

2、Pillar

動態數據,給特定的minion指定特定的數據。只有指定的minion本身能看到本身的數據。

?
1
salt '*' pillar.items

開啓系統自帶,修改配置文件

?
1
vim /etc/salt/master

重啓systemctl restart salt-master

執行salt '*' pillar.items 能夠看到系統自帶的item

piller存在文件路徑設置

mkdir /srv/pillar

重啓systemctl restart salt-master

實現pillar流程

1)建立一個piller文件,python jinja2寫法

?
1
2
3
mkdir /srv/pillar/web
cd /srv/pillar/web
vim apache.sls
?
1
2
3
4
5
{% if grains[ 'os' ] == 'CentOS' %}
apache: httpd
{% elif grains[ 'os' ] == 'Debian' %}
apache: apache2
{% endif %}

2)建立TOP FILE文件

?
1
vim /srv/pillar/top .sls
?
1
2
3
base:
   'linux-node2.example.com' :
     - web.apache
?
1
2
salt '*' saltutil.refresh_pillar  # 刷新
salt '*' pillar.items apache

目標選擇

?
1
salt -I 'apache:httpd' test . ping

 

3、Grains VS Pillar


 

  

 

 

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

  • Saltstack遠程執行

語法例:salt '*' cmd.run 'w'

 -  命令:salt

 -  目標:'*'

 -  模塊:cmd.run,自帶150+模塊,也能夠本身寫模塊

 -  返回:執行後結果返回,Returnners組件

 

一、指定目標(targeting)

官網文檔:https://docs.saltstack.com/en/latest/topics/targeting/index.html

兩種定位方法:一種和minion ID有關,一種和monion ID無關

    1)minion ID有關的方法

  指定具體的minion ID

?
1
salt 'linux-node2.example.com' test . ping

  通配符

?
1
2
3
4
5
6
salt '*' test . ping 
salt 'linux-node2*' test . ping
salt 'linux-node[1|2].example.com' test . ping
salt 'linux-node[1-2].example.com' test . ping
salt 'linux-node[!2].example.com' test . ping
salt 'linux-node?.example.com' test . ping

  列表

?
1
salt -L 'linux-node1.example.com,linux-node2.example.com' test . ping

  正則表達式

?
1
2
salt -E 'linux-(node1|node2)*' test . ping
salt -E 'linux-(node1|node2).example.com' test . ping

備註: 全部匹配目標的方式,均可以用到top file裏面來指定目標。

minion ID設置方案:IP地址、根據業務來進行設置

?
1
2
3
4
5
6
例:
redis-node1-redis04-idc04-h5web.example.com
redis-node1  # redis第一個節點
redis04  # 集羣
idc04  # 機房
h5web  # 業務線

   

    2)minion ID無關的方法

  IP地址、子網

?
1
2
salt -S 192.168.137.12 test . ping
salt -S 192.168.137.0 /24 test . ping

  分組,須要配置master文件

?
1
vim /etc/salt/master

重啓systemctl restart salt-master

?
1
salt -N web test . ping

  混合匹配

官方文檔 https://docs.saltstack.com/en/latest/topics/targeting/compound.html

  批處理 ,可用於重啓全部主機或進程場景,百分比或固定數量的一點一點重啓主機或進程

官方文檔 https://docs.saltstack.com/en/latest/topics/targeting/batch.html

 

二、執行模塊

官網文檔 https://docs.saltstack.com/en/latest/ref/modules/all/index.html#all-salt-modules

列出salt全部模塊,以及如何使用的幫助文檔

經過yum默認安裝salt全部模塊存放路徑 /usr/lib/python2.7/site-packages/salt/modules(centos 7)

例:

?
1
2
3
4
5
6
7
8
9
10
11
salt '*' network.active_tcp  # 列出全部主機運行的tcp鏈接
salt '*' network.arp  # 列出全部主機arp
 
salt '*' service.available sshd  # 列出全部主機sshd
salt '*' service.get_all  # 列出全部主機的全部運行服務
salt '*' service.status sshd  # 列出全部主機sshd運行狀態
 
salt- cp '*' /etc/hosts /tmp/test  # 將master上/etc/hosts文件拷貝到全部主機的/tmp/test
 
salt '*' state.show_top  # 查看top
salt '*' state.single pkg.installed name= lsof  # 全部主機安裝lsof

 

三、返回程序

官方文檔 https://docs.saltstack.com/en/latest/ref/returners/index.html

 1)將返回寫入mysql庫,是由minion直接寫入mysql庫

全部minion安裝python mysql模塊

?
1
2
3
salt '*' state.single pkg.installed name=MySQL-python
salt '*' cmd.run 'yum install MySQL-python -y'

    建立salt庫

?
1
2
3
CREATE DATABASE  `salt`
   DEFAULT CHARACTER SET utf8
   DEFAULT COLLATE utf8_general_ci;
?
1
USE `salt`;

    建立表

?
1
2
3
4
5
6
7
8
9
10
11
--
-- Table structure for table `jids`
--
 
DROP TABLE IF EXISTS `jids`;
CREATE TABLE `jids` (
   `jid` varchar(255) NOT NULL,
   `load` mediumtext NOT NULL,
   UNIQUE KEY `jid` (`jid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE INDEX jid ON jids(jid) USING BTREE;
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
--
-- Table structure for table `salt_returns`
--
 
DROP TABLE IF EXISTS `salt_returns`;
CREATE TABLE `salt_returns` (
   `fun` varchar(50) NOT NULL,
   `jid` varchar(255) NOT NULL,
   ` return ` mediumtext NOT NULL,
   ` id ` varchar(255) NOT NULL,
   `success` varchar(10) NOT NULL,
   `full_ret` mediumtext NOT NULL,
   `alter_time` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
   KEY ` id ` (` id `),
   KEY `jid` (`jid`),
   KEY `fun` (`fun`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
--
-- Table structure for table `salt_events`
--
 
DROP TABLE IF EXISTS `salt_events`;
CREATE TABLE `salt_events` (
` id ` BIGINT NOT NULL AUTO_INCREMENT,
`tag` varchar(255) NOT NULL,
`data` mediumtext NOT NULL,
`alter_time` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`master_id` varchar(255) NOT NULL,
PRIMARY KEY (` id `),
KEY `tag` (`tag`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

    受權

?
1
2
grant all on salt.* to salt@ '%' identified by 'salt@pw' ;
FLUSH PRIVILEGES;
?
1
2
3
exit
mysql -h192.168.137.11 -usalt -psalt@pw salt
show tables;

    配置minion文件

?
1
2
3
4
5
6
vim /etc/salt/minion
mysql.host: '192.168.137.11'
mysql.user: 'salt'
mysql.pass: 'salt@pw'
mysql.db: 'salt'
mysql.port: 3306

重啓 systemctl restart salt-minion

    測試

?
1
salt '*' test . ping -- return mysql

?
1
salt '*' cmd.run 'df -h' -- return mysql

 

四、編寫執行模塊

1)放置路徑

?
1
2
cd /srv/salt
mkdir _modules

2) 命名

文件名就是模塊名

例: my_disk.py

?
1
2
3
4
5
vim /srv/salt/_modules/my_disk .py
def list():
     cmd = 'df -h'
     ret = __salt__[ 'cmd.run' ](cmd)
     return ret

3)刷新

?
1
salt '*' saltutil.sync_modules

會放到指定目標的/var/cache/salt/minion下

4)執行

?
1
salt '*' my_disk.list

 

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

官方文檔 https://docs.saltstack.com/en/latest/topics/states/index.html

 

配置管理之SLS

Salt  State  SLS描述文件(YAML)

名稱ID聲明  默認是name聲明

備註: 一個ID聲明下面。狀態模塊不能重複使用

例:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
apache- install
   pkg.installed:
     - names:
       - httpd
       - httpd-devel
 
apache-service:     # ID聲明,高級狀態,ID必須惟一。
   service.running:  # State聲明 狀態聲明
     - name: httpd   # 選項聲明
     - enable : True 
 
php:  
   pkg.installed

 

經常使用狀態模塊介紹

1)pkg  https://docs.saltstack.com/en/latest/ref/states/all/salt.states.pkg.html#module-salt.states.pkg

pkg.installed  # 安裝
pkg.latest  # 確保最新版本
pkg.remove  # 卸載
pkg.purge  # 卸載並刪除配置文件

# 同時安裝多個包

?
1
2
3
4
5
6
common_packages:
   pkg.installed:
     - pkgs:
       - unzip
       - dos2unix
       - salt-minion: 2015.8.5-1.el6

 

2)file (https://docs.saltstack.com/en/latest/ref/states/all/salt.states.file.html#module-salt.states.file

salt:// 表示當前環境的根目錄。例如:

那麼salt://lamp/files/httpd.conf  表示 /srv/salt/lamp/files/httpd.conf

 

3)service (https://docs.saltstack.com/en/latest/ref/states/all/salt.states.service.html#module-salt.states.service

?
1
2
3
4
redis:
   service.running:
     - enable : True  # 開機自啓動 
     - reload: True  # 重載

 

LAMP架構slat實現安裝、配置、啓動

1.安裝軟件包 pkg

2.修改配置文件 file

3.啓動服務 service

lamp.sls文件內容以下

命令: salt 'linux-node2*' state.sls lamp.lamp

執行結果

 1 linux-node2.example.com:
 2 ----------
 3           ID: lamp-pkg
 4     Function: pkg.installed
 5       Result: True
 6      Comment: 4 targeted packages were installed/updated.
 7               The following packages were already installed: httpd, mariadb-server, mariadb
 8      Started: 12:56:16.178765
 9     Duration: 194279.377 ms
10      Changes:   
11               ----------
12               libzip:
13                   ----------
14                   new:
15                       0.10.1-8.el7
16                   old:
17               php:
18                   ----------
19                   new:
20                       5.4.16-36.3.el7_2
21                   old:
22               php-cli:
23                   ----------
24                   new:
25                       5.4.16-36.3.el7_2
26                   old:
27               php-common:
28                   ----------
29                   new:
30                       5.4.16-36.3.el7_2
31                   old:
32               php-mbstring:
33                   ----------
34                   new:
35                       5.4.16-36.3.el7_2
36                   old:
37               php-mysql:
38                   ----------
39                   new:
40                       5.4.16-36.3.el7_2
41                   old:
42               php-pdo:
43                   ----------
44                   new:
45                       5.4.16-36.3.el7_2
46                   old:
47 ----------
48           ID: apache-config
49     Function: file.managed
50         Name: /etc/httpd/conf/httpd.conf
51       Result: True
52      Comment: File /etc/httpd/conf/httpd.conf is in the correct state
53      Started: 12:59:30.519583
54     Duration: 98.547 ms
55      Changes:   
56 ----------
57           ID: php-config
58     Function: file.managed
59         Name: /etc/php.ini
60       Result: True
61      Comment: File /etc/php.ini is in the correct state
62      Started: 12:59:30.620067
63     Duration: 36.824 ms
64      Changes:   
65 ----------
66           ID: mysql-config
67     Function: file.managed
68         Name: /etc/my.cnf
69       Result: True
70      Comment: File /etc/my.cnf is in the correct state
71      Started: 12:59:30.657074
72     Duration: 58.78 ms
73      Changes:   
74 ----------
75           ID: apache-service
76     Function: service.running
77         Name: httpd
78       Result: True
79      Comment: The service httpd is already running
80      Started: 12:59:30.853149
81     Duration: 40.481 ms
82      Changes:   
83 ----------
84           ID: mysql-service
85     Function: service.running
86         Name: mariadb
87       Result: True
88      Comment: The service mariadb is already running
89      Started: 12:59:30.893939
90     Duration: 33.928 ms
91      Changes:   
92 
93 Summary for linux-node2.example.com
94 ------------
95 Succeeded: 6 (changed=1)
96 Failed:    0
97 ------------
98 Total states run:     6
99 Total run time: 194.548 s
View Code

 

第二種方式:

文件lamp2.sls 內容以下:

命令: salt 'linux-node2*' state.sls lamp.lamp2

執行結果

 1 linux-node2.example.com:
 2 ----------
 3           ID: apache-server
 4     Function: pkg.installed
 5       Result: True
 6      Comment: All specified packages are already installed
 7      Started: 13:13:53.886308
 8     Duration: 665.948 ms
 9      Changes:   
10 ----------
11           ID: apache-server
12     Function: file.managed
13         Name: /etc/httpd/conf/httpd.conf
14       Result: True
15      Comment: File /etc/httpd/conf/httpd.conf is in the correct state
16      Started: 13:13:54.553919
17     Duration: 19.867 ms
18      Changes:   
19 ----------
20           ID: apache-server
21     Function: service.running
22         Name: httpd
23       Result: True
24      Comment: The service httpd is already running
25      Started: 13:13:54.574411
26     Duration: 29.927 ms
27      Changes:   
28 ----------
29           ID: mysql-server
30     Function: pkg.installed
31       Result: True
32      Comment: All specified packages are already installed
33      Started: 13:13:54.604496
34     Duration: 0.771 ms
35      Changes:   
36 ----------
37           ID: mysql-server
38     Function: file.managed
39         Name: /etc/my.cnf
40       Result: True
41      Comment: File /etc/my.cnf is in the correct state
42      Started: 13:13:54.605362
43     Duration: 15.125 ms
44      Changes:   
45 ----------
46           ID: mysql-server
47     Function: service.running
48         Name: mariadb
49       Result: True
50      Comment: The service mariadb is already running
51      Started: 13:13:54.620592
52     Duration: 29.75 ms
53      Changes:   
54 ----------
55           ID: php-config
56     Function: file.managed
57         Name: /etc/php.ini
58       Result: True
59      Comment: File /etc/php.ini is in the correct state
60      Started: 13:13:54.650496
61     Duration: 17.036 ms
62      Changes:   
63 
64 Summary for linux-node2.example.com
65 ------------
66 Succeeded: 7
67 Failed:    0
68 ------------
69 Total states run:     7
70 Total run time: 778.424 ms
View Code

 

配置管理之狀態間關係

狀態間關係:

    1.我依賴誰 require

?
1
2
3
4
5
6
7
8
apache-service:
   service.running:
     - name: httpd
     - enable : True
     - reload: True
     - require:
       - pkg: lamp-pkg  # pkg ID
       - file : apache-config # file ID

    2 我被誰依賴 require_in

?
1
2
3
4
5
6
7
8
9
mysql-config:
   file .managed:
     - name: /etc/my .cnf
     - source : salt: //lamp/files/my .cnf
     - user: root
     - group: root
     - mode: 644
     - require_in:
       - service: mysql-service

    3 我監控誰 watch

?
1
2
3
4
5
6
7
8
9
10
11
apache-service:
   service.running:
     - name: httpd
     - enable : True
     - reload: True
     - require:
       - pkg: lamp-pkg
     - watch :
       - file : apache-config
1. 若果apache-config這個 id 的狀態發生變化就reload
2. 若是不加reload: True,那麼就restart

    4 我被誰監控 watch_in

    5 我引用誰 include

例:lamp第一種方法中,將安裝、配置、啓動分別保存3個文件, 由一個總文件引用

init.sls文件內容

?
1
2
3
4
include:
   - lamp.lamp_pkg
   - lamp.lamp_config
   - lamp.lamp_service

lamp_pkg.sls文件內容

lamp_config.sls文件內容

lamp_service.sls文件內容

執行命令:salt 'linux-node2*' state.sls lamp.init

    6 我擴展誰

 

如何編寫SLS技巧:

1.按狀態分類 若是單獨使用,很清晰。

2.按服務分類 能夠被其餘的SLS include。例如LNMP include mysql的服務。

 

jinja2

文檔:http://docs.jinkan.org/docs/jinja2/

模板包含 變量 或 表達式,兩種分隔符: {% ... %} 和 {{ ... }} 。前者用於執行諸如 for 循環 或賦值的語句,後者把表達式的結果打印到模板上。

salt中如何使用jinja2:

文檔:https://docs.saltstack.com/en/latest/topics/jinja/index.html

  1)告訴File模塊,你要使用jinja  

?
1
2
3
4
5
6
7
8
apache-config:
   file .managed:
     - name: /etc/httpd/conf/httpd .conf
     - source : salt: //lamp/files/httpd .conf
     - user: root
     - group: root
     - mode: 644
     - template: jinja

  2)列出參數列表

?
1
2
3
4
5
6
7
8
9
10
apache-config:
   file .managed:
     - name: /etc/httpd/conf/httpd .conf
     - source : salt: //lamp/files/httpd .conf
     - user: root
     - group: root
     - mode: 644
     - template: jinja
     - defaults:
       PORT: 8080

  3)模板引用

httpd.conf配置文件引用以下

執行命令:salt 'linux-node2*' state.sls lamp.init

執行結果:

 1 linux-node2.example.com:
 2 ----------
 3           ID: lamp-pkg
 4     Function: pkg.installed
 5       Result: True
 6      Comment: All specified packages are already installed
 7      Started: 11:15:02.903236
 8     Duration: 4591.748 ms
 9      Changes:   
10 ----------
11           ID: apache-config
12     Function: file.managed
13         Name: /etc/httpd/conf/httpd.conf
14       Result: True
15      Comment: File /etc/httpd/conf/httpd.conf updated
16      Started: 11:15:07.558365
17     Duration: 90.859 ms
18      Changes:   
19               ----------
20               diff:
21                   --- 
22                   +++ 
23                   @@ -39,7 +39,7 @@
24                    # prevent Apache from glomming onto all bound IP addresses.
25                    #
26                    #Listen 12.34.56.78:80
27                   -Listen 80
28                   +Listen 8080
29                    
30                    #
31                    # Dynamic Shared Object (DSO) Support
32 ----------
33           ID: php-config
34     Function: file.managed
35         Name: /etc/php.ini
36       Result: True
37      Comment: File /etc/php.ini is in the correct state
38      Started: 11:15:07.649429
39     Duration: 63.754 ms
40      Changes:   
41 ----------
42           ID: mysql-config
43     Function: file.managed
44         Name: /etc/my.cnf
45       Result: True
46      Comment: File /etc/my.cnf is in the correct state
47      Started: 11:15:07.713515
48     Duration: 49.273 ms
49      Changes:   
50 ----------
51           ID: apache-service
52     Function: service.running
53         Name: httpd
54       Result: True
55      Comment: Service reloaded
56      Started: 11:15:07.800629
57     Duration: 135.15 ms
58      Changes:   
59               ----------
60               httpd:
61                   True
62 ----------
63           ID: mysql-service
64     Function: service.running
65         Name: mariadb
66       Result: True
67      Comment: The service mariadb is already running
68      Started: 11:15:07.936165
69     Duration: 95.71 ms
70      Changes:   
71 
72 Summary for linux-node2.example.com
73 ------------
74 Succeeded: 6 (changed=2)
75 Failed:    0
76 ------------
77 Total states run:     6
78 Total run time:   5.026 s
View Code

     

 - 模板裏面支持: salt執行模塊 grinas 進行賦值 

例:修改配置文件httpd.conf,將IP地址指向本機IP,經過grains['fqdn_ip4'][0]能夠獲取本機IP地址

salt 'linux-node2*' grains.item fqdn_ip4

 

- 模板裏面支持salt遠程執行模塊

例:修改配置文件httpd.conf,{{ salt['netwrok.hw_addr']('eth0') }}

salt 'linux-node2*' network.hw_addr eth0

執行命令:salt 'linux-node2*' state.sls lamp.init

執行結果

 1 linux-node2.example.com:
 2 ----------
 3           ID: lamp-pkg
 4     Function: pkg.installed
 5       Result: True
 6      Comment: All specified packages are already installed
 7      Started: 11:51:57.213758
 8     Duration: 664.953 ms
 9      Changes:   
10 ----------
11           ID: apache-config
12     Function: file.managed
13         Name: /etc/httpd/conf/httpd.conf
14       Result: True
15      Comment: File /etc/httpd/conf/httpd.conf updated
16      Started: 11:51:57.880642
17     Duration: 82.912 ms
18      Changes:   
19               ----------
20               diff:
21                   --- 
22                   +++ 
23                   @@ -39,7 +39,9 @@
24                    # prevent Apache from glomming onto all bound IP addresses.
25                    #
26                    #Listen 12.34.56.78:80
27                   -Listen 8080
28                   +Listen 192.168.137.12:8080
29                   +
30                   +# MAC IS: 00:0c:29:fd:dd:02
31                    
32                    #
33                    # Dynamic Shared Object (DSO) Support
34 ----------
35           ID: php-config
36     Function: file.managed
37         Name: /etc/php.ini
38       Result: True
39      Comment: File /etc/php.ini is in the correct state
40      Started: 11:51:57.963715
41     Duration: 14.577 ms
42      Changes:   
43 ----------
44           ID: mysql-config
45     Function: file.managed
46         Name: /etc/my.cnf
47       Result: True
48      Comment: File /etc/my.cnf is in the correct state
49      Started: 11:51:57.978393
50     Duration: 12.482 ms
51      Changes:   
52 ----------
53           ID: apache-service
54     Function: service.running
55         Name: httpd
56       Result: True
57      Comment: Service reloaded
58      Started: 11:51:58.021471
59     Duration: 127.043 ms
60      Changes:   
61               ----------
62               httpd:
63                   True
64 ----------
65           ID: mysql-service
66     Function: service.running
67         Name: mariadb
68       Result: True
69      Comment: The service mariadb is already running
70      Started: 11:51:58.148913
71     Duration: 58.592 ms
72      Changes:   
73 
74 Summary for linux-node2.example.com
75 ------------
76 Succeeded: 6 (changed=2)
77 Failed:    0
78 ------------
79 Total states run:     6
80 Total run time: 960.559 ms
View Code

 

 - 模板裏面支持 salt執行模塊 pillar進行賦值

例:修改配置文件httpd.conf,{{ pillar['apache'] }}

salt 'linux-node2*' pillar.item apache 

執行命令:salt 'linux-node2*' state.sls lamp.init

執行結果:

 1 linux-node2.example.com:
 2 ----------
 3           ID: lamp-pkg
 4     Function: pkg.installed
 5       Result: True
 6      Comment: All specified packages are already installed
 7      Started: 12:01:16.490143
 8     Duration: 712.121 ms
 9      Changes:   
10 ----------
11           ID: apache-config
12     Function: file.managed
13         Name: /etc/httpd/conf/httpd.conf
14       Result: True
15      Comment: File /etc/httpd/conf/httpd.conf updated
16      Started: 12:01:17.204369
17     Duration: 93.136 ms
18      Changes:   
19               ----------
20               diff:
21                   --- 
22                   +++ 
23                   @@ -42,6 +42,7 @@
24                    Listen 192.168.137.12:8080
25                    
26                    # MAC IS: 00:0c:29:fd:dd:02
27                   +# pillar: httpd
28                    
29                    #
30                    # Dynamic Shared Object (DSO) Support
31 ----------
32           ID: php-config
33     Function: file.managed
34         Name: /etc/php.ini
35       Result: True
36      Comment: File /etc/php.ini is in the correct state
37      Started: 12:01:17.297764
38     Duration: 17.209 ms
39      Changes:   
40 ----------
41           ID: mysql-config
42     Function: file.managed
43         Name: /etc/my.cnf
44       Result: True
45      Comment: File /etc/my.cnf is in the correct state
46      Started: 12:01:17.315170
47     Duration: 15.217 ms
48      Changes:   
49 ----------
50           ID: apache-service
51     Function: service.running
52         Name: httpd
53       Result: True
54      Comment: Service httpd is already enabled, and is running
55      Started: 12:01:17.331369
56     Duration: 184.591 ms
57      Changes:   
58               ----------
59               httpd:
60                   True
61 ----------
62           ID: mysql-service
63     Function: service.running
64         Name: mariadb
65       Result: True
66      Comment: The service mariadb is already running
67      Started: 12:01:17.516431
68     Duration: 32.057 ms
69      Changes:   
70 
71 Summary for linux-node2.example.com
72 ------------
73 Succeeded: 6 (changed=2)
74 Failed:    0
75 ------------
76 Total states run:     6
77 Total run time:   1.054 s
View Code

 

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

SaltStack項目實戰

  • 系統架構圖

1、初始化

一、salt環境配置,定義基礎環境、生產環境(base、prod)

?
1
2
3
4
5
6
7
8
9
10
vim /etc/salt/master
修改file_roots
file_roots:
   base:
     - /srv/salt/base
   prod:
     - /srv/salt/prod
     
mkdir -p /srv/salt/base
mkdir -p /srv/salt/prod

pillar配置

?
1
2
3
4
5
6
7
8
9
10
vim /etc/salt/master
修改pillar_roots
pillar_roots:
   base:
     - /srv/pillar/base
   pord:
     - /srv/pillar/prod
     
mkdir -p /srv/pillar/base
mkdir -p /srv/pillar/prod

服務重啓 systemctl restart salt-master

 

二、salt base環境初始化:

?
1
2
mkdir -p /srv/salt/base/init  # 環境初始化目錄
mkdir -p /srv/salt/base/init/files  # 配置文件目錄

1)dns配置

準備dns配置文件,放入/srv/salt/base/init/files目錄下

cp /etc/resolv.conf /srv/salt/base/init/files/

?
1
2
3
4
5
6
7
vi /srv/salt/base/init/dns .sls
/etc/resolv .conf:
   file .managed:
     - source : salt: //init/files/resolv .conf
     - user: root
     - gourp: root
     - mode: 644

2)histroy記錄時間

?
1
2
3
4
5
vi /srv/salt/base/init/history .sls
/etc/profile :
   file .append:
     - text:
       - export HISTTIMEFORMAT= "%F %T `whoami` "

3)記錄命令操做

?
1
2
3
4
5
vi /srv/salt/base/init/audit .sls
/etc/bashrc :
   file .append:
     - text:
       - export PROMPT_COMMAND= '{ msg=$(history 1 | { read x y; echo $y; });logger "[euid=$(whoami)]":$(who am i):[`pwd`]"$msg"; }'

4)內核參數優化

?
1
2
3
4
5
6
7
8
9
10
11
12
13
vi /srv/salt/base/init/sysctl .sls
net.ipv4.ip_local_port_range:
   sysctl.present:
     - value: 10000 65000
fs. file -max:
   sysctl.present:
     - value: 2000000
net.ipv4.ip_forward:
   sysctl.present:
     - value: 1
vm.swappiness:
   sysctl.present:
     - value: 0

5)安裝yum倉庫

?
1
2
3
4
5
6
vi /srv/salt/base/init/epel .sls
yum_repo_release:
   pkg.installed:
     - sources:
       - epel-release: http: //mirrors .aliyun.com /epel/epel-release-latest-7 .noarch.rpm
     - unless: rpm -qa | grep epel-release-latest-7

6)安裝zabbix-agent

準備zabbix-agent配置文件,放入/srv/salt/base/init/files目錄下

cp /etc/zabbix/zabbix_agentd.conf /srv/salt/base/init/files/

修改 vi /etc/zabbix/zabbix_agentd.conf

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
vi /srv/salt/base/init/zabbix_agent .sls
zabbix-agent:
   pkg.installed:
     - name: zabbix-agent
   file .managed:
     - name: /etc/zabbix/zabbix_agentd .conf
     - source : salt: //init/files/zabbix_agentd .conf
     - template: jinja
     - backup: minion
     - defaults:
       Server: {{ pillar[ 'zabbix-agent' ][ 'Zabbix_Server' ] }}
       Hostname: {{ grains[ 'fqdn' ] }}
     - require:
       - pkg: zabbix-agent
   service.running:
     - enable : True
     - watch :
       - pkg: zabbix-agent
       - file : zabbix-agent
 
zabbix_agentd.d:
   file .directory:
     - name: /etc/zabbix/zabbix_agentd .d
     - watch_in:
       - service: zabbix-agent
     - require:
       - pkg: zabbix-agent
       - file : zabbix-agent

備註:「- backup: minion」表示備份,若是文件改動,會將以前的文件備份到/var/cache/salt/file_backup目錄下

7)編寫init.sls總文件,引用其它文件

?
1
2
3
4
5
6
7
8
vi /srv/salt/base/init/init .sls
include:
   - init.dns
   - init. history
   - init.audit
   - init.sysctl
   - init.epel
   - init.zabbix_agent

執行命令: salt "*" state.sls init.init

執行結果

  1 linux-node1.example.com:
  2 ----------
  3           ID: /etc/resolv.conf
  4     Function: file.managed
  5       Result: True
  6      Comment: File /etc/resolv.conf is in the correct state
  7      Started: 04:39:32.998314
  8     Duration: 181.548 ms
  9      Changes:   
 10 ----------
 11           ID: /etc/profile
 12     Function: file.append
 13       Result: True
 14      Comment: File /etc/profile is in correct state
 15      Started: 04:39:33.180034
 16     Duration: 6.118 ms
 17      Changes:   
 18 ----------
 19           ID: /etc/bashrc
 20     Function: file.append
 21       Result: True
 22      Comment: Appended 1 lines
 23      Started: 04:39:33.186266
 24     Duration: 6.608 ms
 25      Changes:   
 26               ----------
 27               diff:
 28                   --- 
 29                   
 30                   +++ 
 31                   
 32                   @@ -90,3 +90,4 @@
 33                   
 34                        unset -f pathmunge
 35                    fi
 36                    # vim:ts=4:sw=4
 37                   +export PROMPT_COMMAND='{ msg=$(history 1 | { read x y; echo $y; });logger "[euid=$(whoami)]":$(who am i):[`pwd`]"$msg"; }'
 38 ----------
 39           ID: net.ipv4.ip_local_port_range
 40     Function: sysctl.present
 41       Result: True
 42      Comment: Updated sysctl value net.ipv4.ip_local_port_range = 10000 65000
 43      Started: 04:39:33.261448
 44     Duration: 212.528 ms
 45      Changes:   
 46               ----------
 47               net.ipv4.ip_local_port_range:
 48                   10000 65000
 49 ----------
 50           ID: fs.file-max
 51     Function: sysctl.present
 52       Result: True
 53      Comment: Updated sysctl value fs.file-max = 2000000
 54      Started: 04:39:33.474197
 55     Duration: 122.497 ms
 56      Changes:   
 57               ----------
 58               fs.file-max:
 59                   2000000
 60 ----------
 61           ID: net.ipv4.ip_forward
 62     Function: sysctl.present
 63       Result: True
 64      Comment: Updated sysctl value net.ipv4.ip_forward = 1
 65      Started: 04:39:33.596905
 66     Duration: 35.061 ms
 67      Changes:   
 68               ----------
 69               net.ipv4.ip_forward:
 70                   1
 71 ----------
 72           ID: vm.swappiness
 73     Function: sysctl.present
 74       Result: True
 75      Comment: Updated sysctl value vm.swappiness = 0
 76      Started: 04:39:33.632208
 77     Duration: 36.226 ms
 78      Changes:   
 79               ----------
 80               vm.swappiness:
 81                   0
 82 ----------
 83           ID: yum_repo_release
 84     Function: pkg.installed
 85       Result: True
 86      Comment: All specified packages are already installed
 87      Started: 04:39:39.085699
 88     Duration: 12627.626 ms
 89      Changes:   
 90 ----------
 91           ID: zabbix-agent
 92     Function: pkg.installed
 93       Result: True
 94      Comment: Package zabbix-agent is already installed
 95      Started: 04:39:51.713592
 96     Duration: 6.677 ms
 97      Changes:   
 98 ----------
 99           ID: zabbix-agent
100     Function: file.managed
101         Name: /etc/zabbix/zabbix_agentd.conf
102       Result: True
103      Comment: File /etc/zabbix/zabbix_agentd.conf updated
104      Started: 04:39:51.720994
105     Duration: 152.077 ms
106      Changes:   
107               ----------
108               diff:
109                   --- 
110                   +++ 
111                   @@ -90,7 +90,7 @@
112                    #
113                    # Mandatory: no
114                    # Default:
115                   -Server={{ Server }}
116                   +Server=192.168.137.11
117                    
118                    ### Option: ListenPort
119                    #    Agent will listen on this port for connections from the server.
120 ----------
121           ID: zabbix_agentd.d
122     Function: file.directory
123         Name: /etc/zabbix/zabbix_agentd.d
124       Result: True
125      Comment: Directory /etc/zabbix/zabbix_agentd.d is in the correct state
126      Started: 04:39:51.875082
127     Duration: 0.908 ms
128      Changes:   
129 ----------
130           ID: zabbix-agent
131     Function: service.running
132       Result: True
133      Comment: Service restarted
134      Started: 04:39:51.932698
135     Duration: 205.223 ms
136      Changes:   
137               ----------
138               zabbix-agent:
139                   True
140 
141 Summary for linux-node1.example.com
142 -------------
143 Succeeded: 12 (changed=7)
144 Failed:     0
145 -------------
146 Total states run:     12
147 Total run time:   13.593 s
148 linux-node2.example.com:
149 ----------
150           ID: /etc/resolv.conf
151     Function: file.managed
152       Result: True
153      Comment: File /etc/resolv.conf is in the correct state
154      Started: 12:46:38.639870
155     Duration: 182.254 ms
156      Changes:   
157 ----------
158           ID: /etc/profile
159     Function: file.append
160       Result: True
161      Comment: Appended 1 lines
162      Started: 12:46:38.822236
163     Duration: 3.047 ms
164      Changes:   
165               ----------
166               diff:
167                   --- 
168                   
169                   +++ 
170                   
171                   @@ -74,3 +74,4 @@
172                   
173                    
174                    unset i
175                    unset -f pathmunge
176                   +export HISTTIMEFORMAT="%F %T `whoami` "
177 ----------
178           ID: /etc/bashrc
179     Function: file.append
180       Result: True
181      Comment: Appended 1 lines
182      Started: 12:46:38.825423
183     Duration: 3.666 ms
184      Changes:   
185               ----------
186               diff:
187                   --- 
188                   
189                   +++ 
190                   
191                   @@ -90,3 +90,4 @@
192                   
193                        unset -f pathmunge
194                    fi
195                    # vim:ts=4:sw=4
196                   +export PROMPT_COMMAND='{ msg=$(history 1 | { read x y; echo $y; });logger "[euid=$(whoami)]":$(who am i):[`pwd`]"$msg"; }'
197 ----------
198           ID: net.ipv4.ip_local_port_range
199     Function: sysctl.present
200       Result: True
201      Comment: Updated sysctl value net.ipv4.ip_local_port_range = 10000 65000
202      Started: 12:46:39.011409
203     Duration: 132.499 ms
204      Changes:   
205               ----------
206               net.ipv4.ip_local_port_range:
207                   10000 65000
208 ----------
209           ID: fs.file-max
210     Function: sysctl.present
211       Result: True
212      Comment: Updated sysctl value fs.file-max = 2000000
213      Started: 12:46:39.144117
214     Duration: 33.556 ms
215      Changes:   
216               ----------
217               fs.file-max:
218                   2000000
219 ----------
220           ID: net.ipv4.ip_forward
221     Function: sysctl.present
222       Result: True
223      Comment: Updated sysctl value net.ipv4.ip_forward = 1
224      Started: 12:46:39.177821
225     Duration: 43.489 ms
226      Changes:   
227               ----------
228               net.ipv4.ip_forward:
229                   1
230 ----------
231           ID: vm.swappiness
232     Function: sysctl.present
233       Result: True
234      Comment: Updated sysctl value vm.swappiness = 0
235      Started: 12:46:39.221788
236     Duration: 39.882 ms
237      Changes:   
238               ----------
239               vm.swappiness:
240                   0
241 ----------
242           ID: yum_repo_release
243     Function: pkg.installed
244       Result: True
245      Comment: All specified packages are already installed
246      Started: 12:46:47.608597
247     Duration: 13989.554 ms
248      Changes:   
249 ----------
250           ID: zabbix-agent
251     Function: pkg.installed
252       Result: True
253      Comment: Package zabbix-agent is already installed
254      Started: 12:47:01.598548
255     Duration: 1.265 ms
256      Changes:   
257 ----------
258           ID: zabbix-agent
259     Function: file.managed
260         Name: /etc/zabbix/zabbix_agentd.conf
261       Result: True
262      Comment: File /etc/zabbix/zabbix_agentd.conf updated
263      Started: 12:47:01.600712
264     Duration: 82.425 ms
265      Changes:   
266               ----------
267               diff:
268                   --- 
269                   +++ 
270                   @@ -90,8 +90,6 @@
271                    #
272                    # Mandatory: no
273                    # Default:
274                   -# Server=
275                   -
276                    Server=192.168.137.11
277                    
278                    ### Option: ListenPort
279                   @@ -117,7 +115,7 @@
280                    # Mandatory: no
281                    # Range: 0-100
282                    # Default:
283                   -StartAgents=3
284                   +# StartAgents=3
285                    
286                    ##### Active checks related
287                    
288                   @@ -133,7 +131,7 @@
289                    # Default:
290                    # ServerActive=
291                    
292                   -#ServerActive=192.168.137.11
293                   +ServerActive=192.168.137.11
294                    
295                    ### Option: Hostname
296                    #    Unique, case sensitive hostname.
297                   @@ -144,7 +142,7 @@
298                    # Default:
299                    # Hostname=
300                    
301                   -Hostname=linux-node2
302                   +Hostname=Zabbix server
303                    
304                    ### Option: HostnameItem
305                    #    Item used for generating Hostname if it is undefined. Ignored if Hostname is defined.
306                   @@ -174,7 +172,7 @@
307                    #
308                    # Mandatory: no
309                    # Default:
310                   -HostMetadataItem=system.uname
311                   +# HostMetadataItem=
312                    
313                    ### Option: RefreshActiveChecks
314                    #    How often list of active checks is refreshed, in seconds.
315 ----------
316           ID: zabbix_agentd.d
317     Function: file.directory
318         Name: /etc/zabbix/zabbix_agentd.d
319       Result: True
320      Comment: Directory /etc/zabbix/zabbix_agentd.d is in the correct state
321      Started: 12:47:01.684357
322     Duration: 0.93 ms
323      Changes:   
324 ----------
325           ID: zabbix-agent
326     Function: service.running
327       Result: True
328      Comment: Service restarted
329      Started: 12:47:01.751277
330     Duration: 275.781 ms
331      Changes:   
332               ----------
333               zabbix-agent:
334                   True
335 
336 Summary for linux-node2.example.com
337 -------------
338 Succeeded: 12 (changed=8)
339 Failed:     0
340 -------------
341 Total states run:     12
342 Total run time:   14.788 s
View Code

8)建立top文件

?
1
2
3
4
vi /srv/salt/base/top .sls
base:
   '*' :
     - init.init

測試 salt "*" state.highstate test=True

執行 salt "*" state.highstate

 

三、pillar base初始化

1)zabbix agent配置,指定zabbix server地址,用於sls文件引用

?
1
2
3
4
mkdir -p /srv/pillar/base/zabbix
vi /srv/pillar/base/zabbix/agent .sls
zabbix-agent:
   Zabbix_Server: 192.168.137.11

編寫top,引用/srv/pillar/base/zabbix/agent文件

?
1
2
3
4
vi /srv/pillar/base/top .sls
base:
   '*' :
     - zabbix.agent

測試 salt '*' pillar.items

 

2、haproxy

官網 http://www.haproxy.com/

?
1
2
3
4
5
6
7
8
9
mkdir -p /srv/salt/prod/modules/haproxy
mkdir -p /srv/salt/prod/modules/keepalived
mkdir -p /srv/salt/prod/modules/memcached
mkdir -p /srv/salt/prod/modules/nginx
mkdir -p /srv/salt/prod/modules/php
mkdir -p /srv/salt/prod/modules/pkg
mkdir -p /srv/salt/prod/cluster
mkdir -p /srv/salt/prod/modules/haproxy/files/
mkdir -p /srv/salt/prod/cluster/files

1)系統gcc編譯包等

?
1
2
3
4
5
6
7
8
9
10
11
12
13
vi /srv/salt/prod/pkg/make .sls
make -pkg:
   pkg.installed:
     - names:
       - gcc
       - gcc -c++
       - glibc
       - make
       - autoconf
       - openssl
       - openssl-devel
       - pcre
       - pcre-devel

2) 自安裝

?
1
2
3
4
5
6
cd /usr/local/src    
tar xvf haproxy-1.6.3. tar .gz
cd haproxy-1.6.3/
make TARGET=linux2628 PREFIX= /usr/local/haproxy-1 .6.3
make install PREFIX= /usr/local/haproxy-1 .6.3
ln -s /usr/local/haproxy-1 .6.3 /usr/local/haproxy

修改啓動腳本,放入salt下

?
1
2
3
vi /usr/local/src/haproxy-1 .6.3 /examples/haproxy .init
BIN= /usr/local/haproxy/sbin/ $BASENAME
cp /usr/local/src/haproxy-1 .6.3 /examples/haproxy .init /srv/salt/prod/modules/haproxy/files/

haproxy-1.6.3.tar.gz安裝包放入/srv/salt/prod/modules/haproxy/files/目錄下

3)建立install.sls文件,用於安裝haproxy

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
vi /srv/salt/prod/modules/haproxy/install .sls
include:
   - modules.pkg. make
   
haproxy- install :
   file .managed:
     - name: /usr/local/src/haproxy-1 .6.3. tar .gz
     - source : salt: //modules/haproxy/files/haproxy-1 .6.3. tar .gz
     - mode: 755
     - user: root
     - group: root
   cmd.run:
     - name: cd /usr/local/src && tar zxf haproxy-1.6.3. tar .gz && cd haproxy-1.6.3 && make TARGET=linux2628 PREFIX= /usr/local/haproxy-1 .6.3 && make install PREFIX= /usr/local/haproxy-1 .6.3 && ln -s /usr/local/haproxy-1 .6.3 /usr/local/haproxy
     - unless: test -L /usr/local/haproxy
     - require:
       - pkg: make -pkg
       - file : haproxy- install
 
haproxy-init:
   file .managed:
     - name: /etc/init .d /haproxy
     - source : salt: //modules/haproxy/files/haproxy .init
     - mode: 755
     - user: root
     - group: root
     - require_in:
       - file : haproxy- install
   cmd.run:
     - name: chkconfig --add haproxy
     - unless: chkconfig --list| grep haproxy
  
net.ipv4.ip_nonlocal_bind:
   sysctl.present:
     - value: 1
 
haproxy-config- dir :
   file .directory:
     - name: /etc/haproxy
     - mode: 755
     - user: root
     - group: root

備註: 「- unless」  若是unless後面的命令返回爲True,那麼就不執行當前狀態命令

4)建立haproxy配置文件

建立haproxy-outside.sls文件,用於配置haproxy

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
vi /srv/salt/prod/cluster/haproxy-outside .sls
include:
   - modules.haproxy. install
 
haproxy-service:
   file .managed:
     - name: /etc/haproxy/haproxy .cfg
     - source : salt: //cluster/files/haproxy-outside .cfg
     - user: root
     - group: root
     - mode: 644
   service.running:
     - name: haproxy
     - enable : True
     - reload: True
     - require:
       - cmd: haproxy- install
     - watch :
       - file : haproxy-service

5)配置top file

?
1
2
3
4
5
6
7
vi /srv/pillar/base/top .sls
base:
   '*' :
     - zabbix.agent
prod:
   'linux-node*' :
     - cluster.haproxy-outside

測試 salt "*" state.highstate test=True

執行 salt "*" state.highstate

結果:

 

3、keepalived

1)建立files目錄,將keepalived-1.2.17.tar.gz安裝包、keepalived.sysconfig、keepalived.init放入

?
1
mkdir -p /srv/salt/prod/modules/keepalived/files

2)建立install.sls文件

執行命令:salt '*' state.sls modules.keepalived.install saltenv=prod

3)建立keepalived配置文件haproxy-outside-keepalived.conf

建立haproxy-outside-keepalived.sls

4)將keepalived加入top FILE

?
1
2
3
4
5
6
7
8
vi /srv/salt/base/top .sls
base:
   '*' :
     - init.init
prod:
   'linux-node*' :
     - cluster.haproxy-outside
     - cluster.haproxy-outside-keepalived

測試 salt "*" state.highstate test=True

執行 salt "*" state.highstate

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

 

4、memcached

1)建立www用戶

?
1
2
3
4
5
6
7
8
9
10
11
12
13
mkdir -p /srv/salt/prod/modules/user
vi /srv/salt/prod/modules/user/www .sls
www-user-group:
   group.present:
     - name: www
     - gid: 1000
 
   user.present:
     - name: www
     - fullname: www
     - shell: /sbin/nologin
     - uid: 1000
     - gid: 1000

2)libevent,將安裝包放入/srv/salt/prod/modules/libevent/files

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
mkdir -p /srv/salt/prod/modules/libevent/files
vi /srv/salt/prod/modules/libevent/install .sls
libevent- source - install :
   file .managed:
     - name: /usr/local/src/libevent-2 .0.22-stable. tar .gz
     - source : salt: //modules/libevent/files/libevent-2 .0.22-stable. tar .gz
     - user: root
     - group: root
     - mode: 644
   cmd.run:
     - name: cd /usr/local/src && tar zxf libevent-2.0.22-stable. tar .gz && cd libevent-2.0.22-stable &&  . /configure --prefix= /usr/local/libevent && make && make install
     - unless: test -d /usr/local/libevent
     - require:
       - file : libevent- source - install

3)建立files目錄,將memcached-1.4.24.tar.gz安裝包放入

?
1
mkdir -p /srv/salt/prod/modules/memcached/files

4)建立install.sls文件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
vi /srv/salt/prod/modules/memcached/install .sls
include:
   - modules.libevent. install
 
memcached- source - install :
   file .managed:
     - name: /usr/local/src/memcached-1 .4.24. tar .gz
     - source : salt: //modules/memcached/files/memcached-1 .4.24. tar .gz
     - user: root
     - group: root
     - mode: 644
   cmd.run:
     - name: cd /usr/local/src && tar zxf memcached-1.4.24. tar .gz && cd memcached-1.4.24&& . /configure --prefix= /usr/local/memcached -- enable -64bit --with-libevent= /usr/local/libevent && make && make install
     - unless: test -d /usr/local/memcached
     - require:
       - cmd: libevent- source - install
       - file : memcached- source - install

5)負責業務部分的放入一個目錄,如bbs

?
1
2
3
4
5
6
7
8
9
10
11
12
13
mkdir -p /srv/salt/prod/bbs
vi /srv/salt/prod/bbs/memcached .sls
include:
   - modules.memcached. install
   - modules.user.www
 
memcached-service:
   cmd.run:
     - name: /usr/local/memcached/bin/memcached -d -m 128 -p 11211 -c 8096 -u www
     - unless: netstat -ntlp | grep 11211
     - require:
       - cmd: memcached- source - install
       - user: www-user-group

6)將memcached加入top FILE

?
1
2
3
4
5
6
7
8
9
10
11
vi /srv/salt/base/top .sls
base:
   '*' :
     - init.init
prod:
   'linux-node*' :
     - cluster.haproxy-outside
     - cluster.haproxy-outside-keepalived
 
   'linux-node2*' :
     - bbs.memcached

測試 salt "*" state.highstate test=True

執行 salt "*" state.highstate

 

5、php

1)php安裝包和相關文件放入/srv/salt/prod/modules/php/files

?
1
mkdir -p /srv/salt/prod/modules/php/files

2)建立install.sls

vi /srv/salt/prod/modules/php/install.sls

建立php-memcache.sls

vi /srv/salt/prod/modules/php/php-memcache.sls

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
memcache-plugin:
   file .managed:
     - name: /usr/local/src/memcache-2 .2.7.tgz
     - source : salt: //modules/php/files/memcache-2 .2.7.tgz
     - user: root
     - group: root
     - mode: 755
 
   cmd.run:
     - name: cd /usr/local/src && tar zxf memcache-2.2.7.tgz && cd memcache-2.2.7&& /usr/local/php-fastcgi/bin/phpize && . /configure -- enable -memcache --with-php-config= /usr/local/php-fastcgi/bin/php-config &&  make && make install
     - unless: test -f /usr/local/php-fastcgi/lib/php/extensions/ * /memcache .so
   require:
     - file : memcache-plugin
     - cmd: php- install

建立php-redis.sls

vi /srv/salt/prod/modules/php/php-redis.sls

?
1
2
3
4
5
6
7
8
9
10
11
12
13
redis-plugin:
   file .managed:
     - name: /usr/local/src/redis-2 .2.7.tgz
     - source : salt: //modules/php/files/redis-2 .2.7.tgz
     - user: root
     - group: root
     - mode: 755
   cmd.run:
     - name: cd /usr/local/src && tar zxf redis-2.2.7.tgz && cd redis-2.2.7&& /usr/local/php-fastcgi/bin/phpize && . /configure --with-php-config= /usr/local/php-fastcgi/bin/php-config &&  make && make install
     - unless: test -f /usr/local/php-fastcgi/lib/php/extensions/ * /redis .so
   require:
     - file : redis-plugin
     - cmd: php- install

執行命令:salt '*' state.sls modules.php.install saltenv=prod

 

6、nginx

1)nginx安裝包和相關文件放入/srv/salt/prod/modules/nginx/files

?
1
mkdir -p /srv/salt/prod/modules/nginx/files

 

2)建立install.sls

vi /srv/salt/prod/modules/nginx/install.sls

建立service.sls

vi /srv/salt/prod/modules/nginx/service.sls

執行命令:salt '*' state.sls modules.nginx.install saltenv=prod

4)/srv/salt/prod/bbs/files/nginx-bbs.conf

?
1
2
3
4
5
6
7
8
9
10
11
server {
         listen         8080;
         root /usr/local/nginx/html ;
         index index.htm index.html index.php;
         location ~ \.php$
             {
               fastcgi_pass unix: /usr/local/php-fastcgi/php-fpm .sock;
               fastcgi_index index.php;
               include fastcgi.conf;
         }
}

5)/srv/salt/prod/bbs目錄下建立web.sls

執行命令:salt '*' state.sls bbs.web saltenv=prod

6)將php、nginx加入top FILE

vi /srv/salt/base/top.sls

?
1
2
3
4
5
6
7
8
9
10
11
base:
   '*' :
     - init.init
prod:
   'linux-node*' :
     - cluster.haproxy-outside
     - cluster.haproxy-outside-keepalived
     - bbs.web
 
   'linux-node2*' :
     - bbs.memcached

測試 salt "*" state.highstate test=True

執行 salt "*" state.highstate

 

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

SaltStack之Job管理和Runner

配置文件/etc/salt/master

?
1
2
cachedir: /var/cache/salt/master  # cache路徑
keep_jobs: 24  # job保存時間

salt執行模塊官方文檔  https://docs.saltstack.com/en/latest/ref/modules/all/index.html

 

  • 如何將master的返回加入mysql數據庫?

1)數據庫表結構建立可參考 http://www.cnblogs.com/shhnwangjian/p/5986964.html 的第三節「返回程序」

2)yum install -y MySQL-python  建立python的mysql模塊

3)修改master配置文件

?
1
2
3
4
5
6
7
vi /etc/salt/master
master_job_cache: mysql
mysql.host: '192.168.137.11'
mysql.user: 'salt'
mysql.pass: 'salt@pw'
mysql.db: 'salt'
mysql.port: 3306

4)重啓  systemctl restart salt-master.service

5)測試:

?
1
2
salt '*' test . ping
數據中查詢 select * from  salt_returns;

 

  • 如何kill salt正在執行的任務?

文檔 https://docs.saltstack.com/en/latest/ref/modules/all/salt.modules.saltutil.html#module-salt.modules.saltutil

salt '*' saltutil.running  # 查看正在運行的任務,找到jid

salt '*' saltutil.kill_job jid  # 根據jid殺掉任務

salt '*' saltutil.clear_cache  # 清除minion緩存

備註:

1)正在執行的salt任務,job id會存在minion端的/var/cache/salt/minion/proc目錄下

2)正在執行的salt任務,根據上面master cache的配置,Job的路徑/var/cache/salt/master/jobs目錄下

 

salt runners

官方文檔 https://docs.saltstack.com/en/latest/ref/runners/index.html

命令:salt-run

舉例:

?
1
2
salt-run jobs.list_jobs  # 列出當前保存在job cache中的歷史執行任務
salt-run jobs.lookup_jid jid  # 查看歷史jid執行結果

備註: 咱們經過salt命令開頭執行時,全部的命令master端分發至minion端,由minion端本身執行,若是一個模塊在master存在,在minion端不存在,就會出現執行失敗的狀況。爲了解決這個問題,提供salt runners模塊,它是將全部的命令在master端執行。

salt-run manage.status  #  查看minion的狀態

?
1
2
salt-run manage.down
salt-run manage.up

salt-run manage.versions  #  查看minion的版本

 

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

SaltStack之無Master和多Master

  • Masterless架構,無Master

實現方式:

1)關閉minion進程

2)修改配置文件

?
1
2
vi /etc/salt/minion
file_client: local

備註:其它配置項如file_roots、pillar_roots跟master同樣,區別在於上面的配置項,將從master獲取cache數據,改爲了從本地獲取cache數據。

3)編寫SLS文件

4)執行命令:salt-call --local state.highstate

 

  • 多master架構

實現方式:

1)minion配置

?
1
2
3
4
vi /etc/salt/minion
master:
   - 192.168.137.11
   - 192.168.137.21

2)SLS使用git或者SVN管理

另外一種方式: NFS共享keys 、file_roots、pillar_roots,可是不安全。

 

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

  • Saltstack之Syndic

使用條件:

一、salt syndic必須運行在一臺master上

二、salt syndic必須依賴更高級的master

安裝

?
1
yum install -y salt-syndic

配置

?
1
2
vi /etc/salt/master
syndic_master: 192.168.137.12

備註:syndic和master共用一個配置文件

重啓master: systemctl restart salt-master

啓動sydic: systemctl start salt-syndic

 

更高級master修改配置(上圖中第一排的master)

?
1
2
vi /etc/salt/master
order_masters: True  # 管理syndic

啓動高級master:systemctl start salt-master

 

使用

1)認證,master與syndic須要認證

?
1
salt-key -A

2)master執行命令,經過syndic分發到個minion,而後返回結果

 

重點:syndic的file_roots和pillar_rotts必須與高級master一致。

缺點:高級master並不知道本身到底有多少minion。

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

  • Saltstack之SSH

安裝

?
1
yum install -y salt- ssh

官方文檔  https://docs.saltstack.com/en/latest/topics/ssh/index.html

 

配置

管理/etc/salt/roster文件,配置須要管理的全部主機

?
1
2
3
4
5
6
7
8
9
10
vi /etc/salt/roster
linux-node1.example.com:
   host: 192.168.137.11
   user: root
   port: 22
   
linux-node2.example.com:
   host: 192.168.137.12
   user: root
   port: 22

如何經過證書認證?

1)執行 salt-ssh '*' test.ping -i,提示輸入密碼;

2)用戶輸入一次密碼後salt-ssh會將公鑰發送到對應主機,例如:/root/.ssh/authorized_keys;

3)/etc/salt/pki/master/ssh目錄下存master公鑰和私鑰。

備註:取消證書提示

?
1
2
vi /root/ . ssh /config
StricHostKeyChecking no

 

命令

?
1
salt- ssh '*' -r 'df -h'  # -r參數直接執行Linux命令

 

使用場景

一、不使用minion,經過salt-ssh控制全部主機

二、minion升級、重啓,經過salt-ssh能夠實現

 

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

Saltstack-API

官方文檔 https://docs.saltstack.com/en/latest/ref/netapi/all/salt.netapi.rest_cherrypy.html

參數:http://salt-api.readthedocs.io/en/latest/ref/netapis/all/saltapi.netapi.rest_cherrypy.html#a-rest-api-for-salt

使用條件:1)https調用,須要生成證書  2)配置文件 3)使用PAM驗證 4)啓動salt-api

 

安裝

?
1
yum install -y salt-api

 

實現方式

1)建立用戶useradd -M -s /sbin/nologin saltapi

2)設置密碼passwd saltapi

3)生成自簽名證書

cd /etc/pki/tls/certs

mv localhost.crt /tmp

make testcert

cd /etc/pki/tls/private

若是上面生成證書時輸入了密碼,須要取消密碼

openssl rsa -in localhost.key  -out salt_nopass.key

4)安裝Cherrypy模塊,版本3.2.6

?
1
pip install Cherrypy==3.2.6

備註:centos六、7可使用3.2.6版本,centos5安裝時不要選版本號

5)修改master配置文件

?
1
2
vi /etc/salt/master
default_include: master.d/*.conf

6)建立api配置文件

?
1
2
3
4
5
6
7
cd /etc/salt/master .d/
vi api.conf
rest_cherrypy:
   host: 192.168.137.11
   port: 8000
   ssl_crt: /etc/pki/tls/certs/localhost .crt
   ssl_key: /etc/pki/tls/private/salt_nopass .key

備註:若是加disable_ssl: True,能夠經過http請求。

性能優化:

?
1
2
thread_pool: 100
socket_queue_size: 30

7)認證文件

?
1
2
3
4
5
6
7
vi eauth.conf
external_auth:
   pam:
     saltapi:
       - .*
       - '@wheel'
       - '@runner'

備註: .*  # 全部模塊可執行, '@wheel'  # salt key

centos5.9上yum安裝的salt,eauth.conf配置須要注意,以下配置

?
1
2
3
4
5
6
7
8
9
10
external_auth:
   pam:
     saltapi:
       - .*
       - '@local'
       - '@local_async'
       - '@wheel'
       - '@wheel_async'
       - '@runner'
       - '@runner_async'

8)重啓master

?
1
systemctl restart salt-master.service

9)啓動api

?
1
systemctl restart salt-api

10)須要修改master的配置對saltapi用戶進行受權

?
1
2
3
4
5
6
7
8
9
[root@test1 ~] # vim /etc/salt/master
external_auth:
   pam:
     saltapi:
       - .*
       - '@wheel'
[root@test1 ~] # /etc/init.d/salt-master restart
Stopping salt-master daemon:                               [  OK  ]
Starting salt-master daemon:                               [  OK  ]

 

使用介紹

1)登陸測試,使用curl請求

?
1
2
3
4
5
curl -k https: //192 .168.137.11:8000 /login \
     -H 'Accept: application/x-yaml' \
     -d username=saltapi \
     -d password=saltapi \
     -d eauth=pam

登陸成功後系統返回token,用於後續交互使用。

2)獲取minion資產數據測試,節點爲linux-node1.example.com主機

?
1
2
3
curl -k https: //192 .168.137.11:8000 /minions/linux-node1 .example.com \
     -H 'Accept: application/x-yaml' \
     -H 'X-Auth-Token: token內容'

3)查看全部minion存活主機

?
1
2
3
4
5
curl -k https: //192 .168.137.11:8000/ \
     -H 'Accept: application/x-yaml' \
     -H 'X-Auth-Token: token內容' \
     -d client= 'runner' \
     -d fun= 'manage.status'

備註:client='runner'指的是在master執行,client='local'指的是在minion執行

4)ping測試

?
1
2
3
4
5
6
curl -k https: //192 .168.137.11:8000/ \
     -H 'Accept: application/x-yaml' \
     -H 'X-Auth-Token: token內容' \
     -d client= 'local' \
     -d tgt= '*' \
     -d fun= 'test.ping'

tgt表示目標,能夠指定某一臺minion

5)查看jobs

?
1
2
3
curl -k https: //192 .168.137.11:8000 /jobs \
     -H 'Accept: application/x-yaml' \
     -H 'X-Auth-Token: token內容'

6)查看具體一個jobs的執行結果

?
1
2
3
curl -k https: //192 .168.137.11:8000 /jobs/jobid \
     -H 'Accept: application/x-yaml' \
     -H 'X-Auth-Token: token內容'

 

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

Saltstack異步執行命令

salt執行命令有時候會有超時的問題,就是命令下發下去了,部分主機沒有返回信息,這時候就很難判斷命令或任務是否執行成功。所以,salt提供異步執行的功能,發出命令後當即返回一個jid。而後咱們就能夠根據這個jid來查詢任務是否執行成功。

命令行實現異步

參數--async,返回job ID,根據job ID咱們能夠查詢執行結果。

?
1
salt --async '*' test . ping

?
1
salt-run jobs.lookup_jid 20161117163153353501

-v參數在返回結果的同時,一同返回本次任務的jid,若是超時仍是會返回jid 

?
1
salt - v '*' test . ping

 

API實現異步

任務執行代碼樣例,經過async方法執行異步命令獲取返回job id,經過job方法查看執行結果。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import requests
import json
 
def async(fun, tgt):
     "" "
     異步任務,獲取jid
     "" "
     params = { 'client' : 'local_async' , 'fun' : fun, 'tgt' : tgt}
     headers = { 'X-Auth-Token' : 登錄時獲取的token}
     try:
         ret = requests.post(https: //ip :port/, data=params, headers=headers, verify=False)
         ret = json.loads(ret.text)
         return ret[ 'return' ][0][ 'jid' ]
     except Exception as err:
         print err
         
def jobs_all(jid=None):
     "" "
     job_id=None, 查看salt cache中全部的job任務的執行結果
     job_id傳值時,查看指定job id 的執行結果
     "" "
     headers = { 'X-Auth-Token' : 登錄時獲取的token}
     try:
         if jid is None:
             ret = requests.get(https: //ip :port /jobs , headers=headers, verify=False)
         else :
             ret = requests.get( 'https://ip:port/jobs' + jid, headers=headers, verify=False)
         ret = json.loads(ret.text)
         return ret
     except Exception as err:
         logger.error(err)
         
jid = async( 'test.ping' , '*' )
jobs_all()
jobs_all(jid=jid)

 

查看官方文檔獲取詳細幫助 https://docs.saltstack.com/en/latest/ref/netapi/all/salt.netapi.rest_cherrypy.html#id1

 

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

在windows下經過Salt-Minion-xxxx.xx.x-AMD64-Setup.exe安裝salt-minion的時候,默認是安裝並開機啓動salt-minion服務。可是若是以服務的方式啓動salt-minion的話,windows的可視化操做是不能被控制的。爲了可以經過salt-minion來操控windows的可視化界面,須要禁用salt-minion服務,而且用進程的方式啓動salt-minion。

解決方案

1. 開始>>運行>>services.msc  將salt-minion服務給中止並將啓動類型設爲手動

2.命令行方式運行C:\salt\salt-minion.exe

3.將C:\salt\salt-minion.exe加入啓動,之後服務器重啓能夠實現salt自啓動

相關文章
相關標籤/搜索