saltstack有3大功能:远程执行,配置管理,云管理
其中远程执行又可分解为:目标,模块,返回 这3个部分。
比如下面语句
[root@master ~]# salt '*' test.ping
minion01:
True
minion02:
True
[root@master ~]# salt '*' cmd.run 'df -h'
minion02:
Filesystem Size Used Avail Use% Mounted on
/dev/sda3 35G 4.2G 30G 13% /
tmpfs 2.0G 12K 2.0G 1% /dev/shm
/dev/sda1 380M 33M 327M 10% /boot
minion01:
Filesystem Size Used Avail Use% Mounted on
/dev/sda3 35G 4.2G 30G 13% /
tmpfs 2.0G 12K 2.0G 1% /dev/shm
/dev/sda1 380M 33M 327M 10% /boot
[root@master ~]#
其中'*' 是目标,匹配所有已经认证的minion,test.ping 和cmd.run 是模块中的方法,而下面的结果属于返回
今天先讲一下“返回”
返回,英文名称,returner,默认情况下,发送给salt-minion的命令执行结果返回给salt master。其实saltstack returner的接口允许将结果发送给任意系统,比如:mysql,redis,syslog。
--return syslog 表示minion将结果返回给自己的syslog
[root@master ~]# salt '*' cmd.run 'df -h' --return syslog
minion01:
Filesystem Size Used Avail Use% Mounted on
/dev/sda3 35G 4.2G 30G 13% /
tmpfs 2.0G 12K 2.0G 1% /dev/shm
/dev/sda1 380M 33M 327M 10% /boot
minion02:
Filesystem Size Used Avail Use% Mounted on
/dev/sda3 35G 4.2G 30G 13% /
tmpfs 2.0G 12K 2.0G 1% /dev/shm
/dev/sda1 380M 33M 327M 10% /boot
[root@master ~]#
下面查看minion的系统日志,可以看到上面返回的结果
[root@minion02 ~]# tail -f /var/log/messages
Dec 25 03:36:01 minion02 rsyslogd: [origin software="rsyslogd" swVersion="5.8.10" x-pid="1802" x-info="http://www.rsyslog.com"] rsyslogd was HUPed
Dec 25 13:49:23 minion02 python2.6: {"fun_args": ["df -h"], "jid": "20161225134925942528", "return": "Filesystem Size Used Avail Use% Mounted on\n/dev/sda3 35G 4.2G 30G 13% /\ntmpfs
2.0G 12K 2.0G 1% /dev/shm\n/dev/sda1 380M 33M 327M 10% /boot", "retcode": 0, "success": true, "fun": "cmd.run", "id": "minion02"}
其中
jid,你可以把它简单理解为一个任务编号
return:Filesystem # 表示返回到文件系统里,也就是系统日志里
retcode:0 #表示返回结果状态码
success:true #成功与否
fun:cmd.run #执行的函数模块
这个返回的日志存储在了minion的系统日志上,而不是master的系统日志上
假如,我们想让minion把返回的结果直接存到mysql里面,然后进行二次开发,从mysql库里找出哪些minion执行成功,哪些执行失败
操作步骤如下
1、准备一台mysql机器
2、mysql服务器建库建表
3、所有minion安装mysql-python模块
4、minion更改配置文件,连接mysql
5、master发送命令测试
这里使用第4台机器,IP地址为10.0.1.174作为mysql服务器
[root@mysql ~]# rpm -qa|grep mysql
mysql-libs-5.1.73-3.el6_5.x86_64
[root@mysql ~]# yum install mysql mysql-server -y
启动mysql服务,更改root密码
[root@mysql ~]# /etc/init.d/mysqld start
Initializing MySQL database: WARNING: The host 'mysql' could not be looked up with resolveip.
This probably means that your libc libraries are not 100 % compatible
with this binary MySQL version. The MySQL daemon, mysqld, should work
normally with the exception that host name resolving will not work.
This means that you should use IP addresses instead of hostnames
when specifying MySQL privileges !
Installing MySQL system tables...
OK
Filling help tables...
OK To start mysqld at boot time you have to copy
support-files/mysql.server to the right place for your system PLEASE REMEMBER TO SET A PASSWORD FOR THE MySQL root USER !
To do so, start the server, then issue the following commands: /usr/bin/mysqladmin -u root password 'new-password'
/usr/bin/mysqladmin -u root -h mysql password 'new-password' Alternatively you can run:
/usr/bin/mysql_secure_installation which will also give you the option of removing the test
databases and anonymous user created by default. This is
strongly recommended for production servers. See the manual for more instructions. You can start the MySQL daemon with:
cd /usr ; /usr/bin/mysqld_safe & You can test the MySQL daemon with mysql-test-run.pl
cd /usr/mysql-test ; perl mysql-test-run.pl Please report any problems with the /usr/bin/mysqlbug script! [ OK ]
Starting mysqld: [ OK ]
[root@mysql ~]# /usr/bin/mysqladmin -u root password '123456'
[root@mysql ~]#
开始给saltstack建库建表
[root@mysql ~]# mysql -uroot -p123456
CREATE DATABASE `salt`
DEFAULT CHARACTER SET utf8
DEFAULT COLLATE utf8_general_ci;
USE `salt`; 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;
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;
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;
grant all on salt.* to salt@'%' identified by 'salt123';
flush privileges;
salt '*' cmd.run 'yum install MySQL-python -y'
先备份原先的配置
[root@master ~]# salt '*' cmd.run '/bin/cp /etc/salt/minion /etc/salt/minion.01'
minion01:
minion02:
[root@master ~]#
然后登录到minion机器上修改文件,执行如下命令
cat >> /etc/salt/minion <<EOF
mysql.host: '10.0.1.174'
mysql.user: 'salt'
mysql.pass: 'salt123'
mysql.db: 'salt'
mysql.port: 3306
EOF
检查确认下
[root@minion01 ~]# tail -6 /etc/salt/minion
#return: mysql
mysql.host: '10.0.1.174'
mysql.user: 'salt'
mysql.pass: 'salt123'
mysql.db: 'salt'
mysql.port: 3306
[root@minion01 ~]#
对其余minion也同样操作
修改完毕后,重启minion服务
重启方法有两种
1、使用命令重启
salt '*' cmd.run '/etc/init.d/salt-minion restart
2、使用模块重启
salt '*' service.restart salt-minion
我们采用第二种重启
[root@master ~]# salt '*' service.restart salt-minion
minion01:
True
minion02:
True
[root@master ~]#
接下来测试是否返回给了mysql
先在master上执行命令,加入--return mysql参数
[root@master ~]# salt '*' test.ping --return mysql
minion02:
True
minion01:
True
[root@master ~]#
然后在mysql上查看结果
可以看到执行了test.ping 这个模块
jid编号是以当前时间格式命名的
return:true 表示返回成功
等一些列信息
mysql> select * from salt_returns\G;
*************************** 1. row ***************************
fun: test.ping
jid: 20161225144720565109
return: true
id: minion02
success: 1
full_ret: {"fun_args": [], "jid": "20161225144720565109", "return": true, "retcode": 0, "success": true, "fun": "test.ping", "id": "minion02"}
alter_time: 2016-12-25 14:47:18
*************************** 2. row ***************************
fun: test.ping
jid: 20161225144720565109
return: true
id: minion01
success: 1
full_ret: {"fun_args": [], "jid": "20161225144720565109", "return": true, "retcode": 0, "success": true, "fun": "test.ping", "id": "minion01"}
alter_time: 2016-12-25 14:47:18
2 rows in set (0.00 sec) ERROR:
No query specified mysql>
以下写法是等价的
[root@master ~]# salt '*' test.ping --return mysql
minion02:
True
minion01:
True
[root@master ~]# salt '*' test.ping --return=mysql
minion01:
True
minion02:
True
[root@master ~]#
如果你不想每次加参数--return mysql 让它自动返回到mysql,可以修改master的配置文件,取消return: mysql这一行的注释,然后重启master服务
minion端的配置文件也有return: mysql这一行,经过我的测试,取消它的注释是没用的
[root@master ~]# tail -2 /etc/salt/master
# Which returner(s) will be used for minion's result:
return: mysql
[root@master ~]#
第二种结构,master把结果返回给mysql ,如下显示
这里我们使用到了salt自带的event,下面一串是搜索到的,看了也是似懂非懂。
event是一个本地的ZeroMQ PUB Interface,event是一个开放的系统,用于发送信息通知salt或其他的操作系统。每个event都有一个标签。事件标签允许快速制定过滤事件。除了标签之外,每个事件都有一个数据结构。这个数据结构是一个dict类型,其中包含关于事件的信息。
event接口测试
先测试下能否从event里取出数据,简单些一个取数据的python脚本,内容如下
[root@master master]# mkdir /scripts
[root@master master]# cd /scripts/
[root@master scripts]# vim salt-event.py
[root@master scripts]# cat salt-event.py
import salt.utils.event
event = salt.utils.event.MasterEvent('/var/run/salt/master')
for data in event.iter_events(full=True):
print data
print '------'
[root@master scripts]#
执行这个脚本
[root@master scripts]# python salt-event.py
新打开一个窗口,使用salt简单执行一个命令
[root@master salt]# salt '*' test.ping
minion01:
True
minion02:
True
[root@master salt]#
刚才窗口可以看到返回的结果,它是一个python字典形式的数据。
[root@master scripts]# python salt-event.py
{'tag': 'salt/event/new_client', 'data': {'_stamp': '2016-12-25T07:35:17.261403'}}
------
{'tag': '20161225153517270106', 'data': {'_stamp': '2016-12-25T07:35:17.270256', 'minions': ['minion01', 'minion02']}}
------
{'tag': 'salt/job/20161225153517270106/new', 'data': {'tgt_type': 'glob', 'jid': '20161225153517270106', 'tgt': '*', '_stamp': '2016-12-25T07:35:17.270458', 'user': 'root',
'arg': [], 'fun': 'test.ping', 'minions': ['minion01', 'minion02']}}
------
{'tag': 'salt/job/20161225153517270106/ret/minion01', 'data': {'fun_args': [], 'jid': '20161225153517270106', 'return': True, 'retcode': 0, 'success': True, 'cmd': '_return',
'_stamp': '2016-12-25T07:35:17.412322', 'fun': 'test.ping', 'id': 'minion01'}}
------
{'tag': 'salt/job/20161225153517270106/ret/minion02', 'data': {'fun_args': [], 'jid': '20161225153517270106', 'return': True, 'retcode': 0, 'success': True, 'cmd': '_return',
'_stamp': '2016-12-25T07:35:17.412489', 'fun': 'test.ping', 'id': 'minion02'}}
------
上面能从event取到数据,那么我们就能把数据取到之后存入mysql里
以上测试没问题后,需要如下操作
为了避免minion直接返回到mysql的干扰,我们把minion端配置文件里连接mysql的信息注释掉,同时也要把master端口return: mysql注释掉。分别重启服务
1、mysql需要建库建表,由于上面的演示已经建库建表完成了,这里就不需要了,但是可以把之前表里的数据清空了
2、因为master要连接数据库了,因此需要安装MySQL-python模块
3、master端写一个从event把数据存入mysql的脚本
4、后台执行此脚本
5、测试
master端安装配置文件
[root@master salt]# yum -y install MySQL-python
Loaded plugins: fastestmirror, refresh-packagekit, security
Setting up Install Process
Loading mirror speeds from cached hostfile
* base: centos.ustc.edu.cn
* epel: mirrors.tuna.tsinghua.edu.cn
* extras: centos.ustc.edu.cn
* updates: centos.ustc.edu.cn
Package MySQL-python-1.2.3-0.3.c1.1.el6.x86_64 already installed and latest version
Nothing to do
[root@master salt]#
master端编写脚本
[root@master salt]# cd /scripts/
[root@master scripts]# ls
salt-event.py
[root@master scripts]# vim salt_event_to_mysql.py
[root@master scripts]# cat salt_event_to_mysql.py
#!/bin/env python
#coding=utf8
# Import python libs
import json
# Import salt modules
import salt.config
import salt.utils.event
# Import third part libs
import MySQLdb
__opts__ = salt.config.client_config('/etc/salt/master')
#create MySQL connect
#conn = MySQLdb.connect(host=__opts__['mysql.host'],user=__opts__['mysql.user'],passwd=__opts__['mysql.pass'],db=__opts__['mysql.db'],port=__opts__['mysql.port']) conn = MySQLdb.connect(host='10.0.1.174',user='salt',passwd='salt123',db='salt',port=3306)
cursor = conn.cursor()
# Listen Salt Master Event System
event = salt.utils.event.MasterEvent(__opts__['sock_dir'])
for eachevent in event.iter_events(full=True):
ret = eachevent['data']
if "salt/job/" in eachevent['tag']:
#Return Event
if ret.has_key('id') and ret.has_key('return'):
#Ignore saltutil.find_job event
if ret['fun'] == "saltutil.find_job":
continue
sql = '''INSERT INTO `salt_returns`
(`fun`,`jid`,`return`,`id`,`success`,`full_ret` )
VALUES (%s,%s,%s,%s,%s,%s)'''
cursor.execute(sql,(ret['fun'],ret['jid'],
json.dumps(ret['return']),ret['id'],
ret['success'],json.dumps(ret)))
cursor.execute("COMMIT")
# Other Event
else:
pass
[root@master scripts]#
master上后端执行此脚本
[root@master scripts]# python salt_event_to_mysql.py &
[1] 30810
[root@master scripts]#
master上执行测试操作
[root@master scripts]# salt '*' test.ping
minion02:
True
minion01:
True
[root@master scripts]#
mysql上查看有新的数据,原先表还是空表。测试之后有了数据
mysql> select * from salt_returns\G;
Empty set (0.00 sec) ERROR:
No query specified mysql> select * from salt_returns\G;
*************************** 1. row ***************************
fun: test.ping
jid: 20161225160554520788
return: true
id: minion01
success: 1
full_ret: {"fun_args": [], "jid": "20161225160554520788", "return": true, "retcode": 0, "success": true, "cmd": "_return", "_stamp": "2016-12-25T08:05:54.705395", "fun": "test.ping", "id": "minion01"}
alter_time: 2016-12-25 16:05:52
*************************** 2. row ***************************
fun: test.ping
jid: 20161225160554520788
return: true
id: minion02
success: 1
full_ret: {"fun_args": [], "jid": "20161225160554520788", "return": true, "retcode": 0, "success": true, "cmd": "_return", "_stamp": "2016-12-25T08:05:54.708870", "fun": "test.ping", "id": "minion02"}
alter_time: 2016-12-25 16:05:52
2 rows in set (0.00 sec) ERROR:
No query specified mysql>
注意点:
1、看到一些文章提到还要在master的配置文件里添加下面几行,但是上面我没有添加,mysql也通过python脚本获取数据了
master配置文件不需要添加以下
mysql.host: '10.0.1.174'
mysql.user: 'salt'
mysql.pass: 'salt123'
mysql.db: 'salt'
mysql.port: 3306
2、下面报错就是没安装MySQL-python模块导致的