1.封装模块
我们可以把很多函数封装在一个模块中这样在我们调用的过程中就可用调用模块中的函数,方便管理
#添加一个模块
[root@server5 keepalived]# cd
[root@server5 ~]# yum install -y mysql-server #安装数据库服务
[root@server5 ~]# salt server6 state.sls httpd.install
[root@server6 ~]# yum search mysql-python
Loaded plugins: product-id, subscription-manager
This system is not registered to Red Hat Subscription Management. You can use subscription-manager to register.
=========================== N/S Matched: mysql-python ===========================
MySQL-python.x86_64 : An interface to MySQL
Name and summary matches only, use "search all" for everything.
[root@server6 ~]# yum install MySQL-python.x86_64 -y
[root@server6 ~]# cd /etc/salt/
[root@server6 salt]# vim minion
814 mysql.host: '172.25.44.5' #master端ip
815 mysql.user: 'salt' #用户
816 mysql.pass: 'westos' #密码
817 mysql.db: 'salt'
818 mysql.port: 3306 #端口
[root@server6 salt]# /etc/init.d/salt-minion restart #修改完配置文件记得重启
Stopping salt-minion:root:server6 daemon: OK
Starting salt-minion:root:server6 daemon: OK
[root@server5 init.d]# /etc/init.d/mysqld start
[root@server5 ~]# vim test.sql
1 CREATE DATABASE `salt`
2 DEFAULT CHARACTER SET utf8
3 DEFAULT COLLATE utf8_general_ci;
4
5 USE `salt`;
6
7 --
8 -- Table structure for table `jids`
9 --
10
11 DROP TABLE IF EXISTS `jids`;
12 CREATE TABLE `jids` (
13 `jid` varchar(255) NOT NULL,
14 `load` mediumtext NOT NULL,
15 UNIQUE KEY `jid` (`jid`)
16 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
17 #CREATE INDEX jid ON jids(jid) USING BTREE;
18
19 --
20 -- Table structure for table `salt_returns`
21 --
22
23 DROP TABLE IF EXISTS `salt_returns`;
24 CREATE TABLE `salt_returns` (
25 `fun` varchar(50) NOT NULL,
26 `jid` varchar(255) NOT NULL,
27 `return` mediumtext NOT NULL,
28 `id` varchar(255) NOT NULL,
29 `success` varchar(10) NOT NULL,
30 `full_ret` mediumtext NOT NULL,
31 `alter_time` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
32 KEY `id` (`id`),
33 KEY `jid` (`jid`),
34 KEY `fun` (`fun`)
35 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
36
37 --
38 -- Table structure for table `salt_events`
39 --
40
41 DROP TABLE IF EXISTS `salt_events`;
42 CREATE TABLE `salt_events` (
43 `id` BIGINT NOT NULL AUTO_INCREMENT,
44 `tag` varchar(255) NOT NULL,
45 `data` mediumtext NOT NULL,
46 `alter_time` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
47 `master_id` varchar(255) NOT NULL,
48 PRIMARY KEY (`id`),
49 KEY `tag` (`tag`)
50 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
[root@server5 ~]# mysql
mysql> grant all on salt.* to salt@'localhost' identified by 'westos'; #授权
Query OK, 0 rows affected (0.00 sec)
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| test |
+--------------------+
3 rows in set (0.00 sec)
[root@server5 ~]# mysql < test.sql #将数据库导入test.sql
[root@server5 ~]# salt 'server6' test.ping --return mysql # 测试返回值
server6:
True
[root@server5 ~]# mysql 登陆数据库
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| salt |
| test |
+--------------------+
4 rows in set (0.00 sec)
mysql> use salt;
mysql> show tables;
+----------------+
| Tables_in_salt |
+----------------+
| jids |
| salt_events |
| salt_returns |
+----------------+
3 rows in set (0.00 sec)
[root@server5 ~]# yum install MySQL-python.x86_64 -y
[root@server5 ~]# vim /etc/salt/master #在master端配置mysql
1073 master_job_cache: mysql
1074 mysql.host: '172.25.44.5'
1075 mysql.user: 'salt'
1076 mysql.pass: 'westos'
1077 mysql.db: 'salt'
1078 mysql.port: 3306
[root@server5 ~]# /etc/init.d/salt-master restart
Stopping salt-master daemon: [ OK ]
Starting salt-master daemon: [ OK ]
[root@server5 ~]# mysql
mysql> grant all on salt.* to salt@localhost identified by 'westos'; # 给本机授权
Query OK, 0 rows affected (0.00 sec)
mysql> flush privileges; # 给本机授权
Query OK, 0 rows affected (0.00 sec)
mysql> use salt;
mysql> select * from salt_returns; # 查看返回值
mysql> Bye
[root@server5 salt]# salt server7 cmd.run 'df -h' #可以通过
server7:
Filesystem Size Used Avail Use% Mounted on
/dev/mapper/VolGroup-lv_root 19G 1.1G 17G 6% /
tmpfs 246M 16K 246M 1% /dev/shm
/dev/vda1 485M 33M 427M 8% /boot
#添加多个模块
[root@server5 ~]# mkdir /srv/salt/_modules
[root@server5 ~]# cd /srv/salt/
[root@server5 salt]# ls
_grains haproxy httpd keepalived _modules nginx pkgs top.sls users
[root@server5 salt]# cd _modules/
[root@server5 _modules]# vim my_disk.py
1 #!/usr/bin/env python
2
3 def df():
4 return __salt__['cmd.run']('df -h')
[root@server5 _modules]# salt '*' saltutil.sync_modules
server7:
- modules.my_disk
server6:
- modules.my_disk
server8:
- modules.my_disk
server5:
- modules.my_disk
[root@server5 salt]# salt '*' my_disk.df #推送,可以看到模块添加成功
server7:
Filesystem Size Used Avail Use% Mounted on
/dev/mapper/VolGroup-lv_root 19G 1.1G 17G 6% /
tmpfs 246M 16K 246M 1% /dev/shm
/dev/vda1 485M 33M 427M 8% /boot
server6:
Filesystem Size Used Avail Use% Mounted on
/dev/mapper/VolGroup-lv_root 19G 990M 17G 6% /
tmpfs 246M 64K 246M 1% /dev/shm
/dev/vda1 485M 33M 427M 8% /boot
server8:
Filesystem Size Used Avail Use% Mounted on
/dev/mapper/VolGroup-lv_root 19G 1.1G 17G 7% /
tmpfs 246M 16K 246M 1% /dev/shm
/dev/vda1 485M 33M 427M 8% /boot
server5:
Filesystem Size Used Avail Use% Mounted on
/dev/mapper/VolGroup-lv_root 19G 1.1G 17G 7% /
tmpfs 246M 96K 246M 1% /dev/shm
/dev/vda1 485M 33M 427M 8% /boot
[root@server8 etc]# cd /tmp/
[root@server8 tmp]# cd /var/cache/
[root@server8 cache]# ls
ldconfig salt yum
[root@server8 cache]# cd salt/
[root@server8 salt]# cd minion/
[root@server8 minion]# ls
accumulator files module_refresh proc
extmods highstate.cache.p pkg_refresh sls.p
[root@server8 minion]# cd extmods/
[root@server8 extmods]# ls
grains modules
[root@server8 extmods]# cd modules/
[root@server8 modules]# ll
total 8
-rw------- 1 root root 73 8月 18 15:58 my_disk.py
-rw------- 1 root root 319 8月 18 16:12 my_disk.pyc
2.横向扩展
搭建top master用来管理各个master,实现了master端的横向扩展,从而减轻了master端的负载压力
[root@server5 salt]# salt-key -d server8 #删除server8的公钥信息
The following keys are going to be deleted:
Accepted Keys:
server8
Proceed? [N/y] Y
Key for minion server8 deleteed.
[root@server5 salt]# salt-key -L
Accepted Keys:
server5
server6
server7
Denied Keys:
Unaccepted Keys:
Rejected Keys:
[root@server8 modules]# /etc/init.d/salt-minion stop
Stopping salt-minion:root:server8 daemon: OK
[root@server8 modules]# chkconfig salt-minion off
[root@server8 modules]# /etc/init.d/haproxy stop
Stopping haproxy: [ OK ]
[root@server8 modules]# /etc/init.d/keepalived stop
Stopping keepalived: [ OK ]
[root@server8 modules]# ps ax
32537 ? Ss 0:00 /usr/sbin/haproxy -D -f /etc/haproxy/haproxy.cfg -p /va
32566 pts/0 R+ 0:00 ps ax
[root@server8 modules]# /etc/init.d/haproxy stop
Stopping haproxy: [ OK ]
[root@server8 ~]# yum install salt-master -y #server8作为top-master
[root@server8 ~]# cd /etc/salt/
[root@server8 salt]# vim master
857 order_masters: True
[root@server8 salt]# /etc/init.d/salt-master start
Starting salt-master daemon: [ OK ]
[root@server8 salt]# salt-key -L
Accepted Keys:
Denied Keys:
Unaccepted Keys:
Rejected Keys:
[root@server5 salt]# yum install -y salt-syndic
[root@server5 salt]# pwd
/etc/salt
[root@server5 salt]# ls
cloud cloud.maps.d master minion.d proxy
cloud.conf.d cloud.profiles.d master.d minion_id proxy.d
cloud.deploy.d cloud.providers.d minion pki roster
[root@server5 salt]# vim master # 写入top master的IP
861 syndic_master: 172.25.44.8
[root@server5 salt]# /etc/init.d/salt-master stop
Stopping salt-master daemon: [ OK ]
[root@server5 salt]# /etc/init.d/salt-master start
Starting salt-master daemon: [ OK ]
[root@server5 salt]# /etc/init.d/salt-syndic #开启syndic服务不然无法交换公钥
Starting salt-syndic daemon: [ OK ]
[root@server8 salt]# salt-key -L
Accepted Keys:
Denied Keys:
Unaccepted Keys:
server5
Rejected Keys:
[root@server8 salt]# salt-key -A
The following keys are going to be accepted:
Unaccepted Keys:
server5
Proceed? [n/Y] Y
Key for minion server5 accepted.
[root@server8 salt]# salt-key -L
Accepted Keys:
server5
Denied Keys:
Unaccepted Keys:
Rejected Keys:
[root@server8 salt]# salt '*' test.ping # ping通的server6,server7,都是server5给提供的
server6:
True
server7:
True
server5:
True
3.测试salt-ssh模块:
[root@server5 salt]# yum install -y salt-ssh
[root@server5 salt]# vim /etc/salt/roster
11 server8:
12 host: 172.25.44.7
13 user: root
14 passwd: westos
[root@server5 salt]# pwd
/etc/salt
[root@server5 salt]# vim master #注释掉这些行
861 syndic_master: 172.25.44.7
1058 #master_job_cache: mysql
1059 #mysql.host: 'localhost'
1060 #mysql.user: 'salt'
1061 #mysql.pass: 'westos'
1062 #mysql.db: 'salt'
1063 #mysql.port: 3306
[root@server5 salt]# salt-ssh '*' test.ping
server7:
True
[root@server5 salt]# salt-ssh 'server7' my_disk.df #直接调用ssh服务可以查看server3的磁盘信息
server7:
Filesystem Size Used Avail Use% Mounted on
/dev/mapper/VolGroup-lv_root 19G 1.1G 17G 6% /
tmpfs 246M 16K 246M 1% /dev/shm
/dev/vda1 485M 33M 427M 8% /boot
4.api认证
[root@server5 salt]# yum install -y salt-api
[root@server7 ~]# /etc/init.d/salt-minion start
[root@server5 salt]# cd /etc/pki/tls
[root@server5 tls]# ls
cert.pem certs misc openssl.cnf private
[root@server5 tls]# cd private/
[root@server5 private]# ls
[root@server5 private]# openssl genrsa 1024
[root@server5 private]# openssl genrsa 1024 > localhost.key #生成localhost.key
Generating RSA private key, 1024 bit long modulus
.......................++++++
...++++++
e is 65537 (0x10001)
[root@server5 certs]# make testcert #生成证书
umask 77 ; \
/usr/bin/openssl req -utf8 -new -key /etc/pki/tls/private/localhost.key -x509 -days 365 -out /etc/pki/tls/certs/localhost.crt -set_serial 0
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:cn
State or Province Name (full name) []:shaanxi
Locality Name (eg, city) [Default City]:xi'an
Organization Name (eg, company) [Default Company Ltd]:westos
Organizational Unit Name (eg, section) []:linux
Common Name (eg, your name or your server's hostname) []:server5
Email Address []:root@localhost
[root@server5 certs]# ls
ca-bundle.crt localhost.crt Makefile
ca-bundle.trust.crt make-dummy-cert renew-dummy-cert
[root@server5 certs]# ll localhost.crt
-rw------- 1 root root 1029 8月 18 17:17 localhost.crt
[root@server5 certs]# pwd
/etc/pki/tls/certs
[root@server5 certs]# cd /etc/salt/
[root@server5 salt]# cd master.d/
[root@server5 master.d]# ls
[root@server5 master.d]# vim api.conf #
1 rest_cherrypy:
2 port: 8000
3 ssl_crt: /etc/pki/tls/certs/localhost.crt
4 ssl_key: /etc/pki/tls/private/localhost.key
[root@server5 master.d]# ll /etc/pki/tls/certs/localhost.crt
-rw------- 1 root root 1029 8月 18 17:17 /etc/pki/tls/certs/localhost.crt
[root@server5 master.d]# ll /etc/pki/tls/private/localhost.key
-rw-r--r-- 1 root root 887 8月 18 17:14 /etc/pki/tls/private/localhost.key
[root@server5 master.d]# vim auto.conf
1 external_auth:
2 pam:
3 saltapi:
4 - '.*'
5 - '@wheel'
6 - '@runner'
7 - '@jobs'
[root@server5 master.d]# useradd saltapi # 建立用户
[root@server5 master.d]# passwd saltapi # 设置密码
Changing password for user saltapi.
New password: #设置自己的密码
BAD PASSWORD: it is based on a dictionary word
BAD PASSWORD: is too simple
Retype new password:
passwd: all authentication tokens updated successfully.
[root@server5 master.d]# /etc/init.d/salt-master restart
Stopping salt-master daemon: [ OK ]
Starting salt-master daemon: [ OK ]
[root@server5 master.d]# /etc/init.d/salt-api start
[root@server5 master.d]# netstat -antlp | grep :8000
tcp 0 0 0.0.0.0:8000 0.0.0.0:* LISTEN 3426/python2.6
tcp 0 0 127.0.0.1:55816 127.0.0.1:8000 TIME_WAIT -
[root@server5 master.d]# curl -sSk https://localhost:8000/login \
> -H 'Accept: application/x-yaml' \
> -d username=saltapi \
> -d password=westos \
> -d eauth=pam #调用curl命令测试
return:
- eauth: pam
expire: 1534628749.629297
perms:
- .*
- '@wheel'
- '@runner'
- '@jobs'
start: 1534585549.6292961
token: d9defd3f9d4a22576030764bd227c4ed0152d204
user: saltapi
[root@server5 master.d]# curl -sSk https://localhost:8000 \
> -H 'Accept: application/x-yaml' \
> -H 'X-Auth-Token: d9defd3f9d4a22576030764bd227c4ed0152d204' \
> -d client=local \
> -d tgt='*' \
> -d fun=test.ping
return:
- server5: true
server6: true
server7: true
[root@server7 ~]# /etc/init.d/nginx stop
Stopping nginx: [ OK ]
[root@server7 ~]# ps ax #nginx服务已关闭
[root@server5 master.d]# vim salt-api.py # 编写脚本测试打印 print sapi.list_all_key()信息
1 # -*- coding: utf-8 -*-
2
3 import urllib2,urllib
4 import time
5
6 try:
7 import json
8 except ImportError:
9 import simplejson as json
10
11 class SaltAPI(object):
12 __token_id = ''
13 def __init__(self,url,username,password):
14 self.__url = url.rstrip('/')
15 self.__user = username
16 self.__password = password
17
18 def token_id(self):
19 ''' user login and get token id '''
20 params = {'eauth': 'pam', 'username': self.__user, 'password': s elf.__password}
21 encode = urllib.urlencode(params)
22 obj = urllib.unquote(encode)
23 content = self.postRequest(obj,prefix='/login')
24 try:
25 self.__token_id = content['return'][0]['token']
26 except KeyError:
27 raise KeyError
28
29 def postRequest(self,obj,prefix='/'):
30 url = self.__url + prefix
31 headers = {'X-Auth-Token' : self.__token_id}
32 req = urllib2.Request(url, obj, headers)
33 opener = urllib2.urlopen(req)
34 content = json.loads(opener.read())
35 return content
36
37 def list_all_key(self):
38 params = {'client': 'wheel', 'fun': 'key.list_all'}
39 obj = urllib.urlencode(params)
40 self.token_id()
41 content = self.postRequest(obj)
42 minions = content['return'][0]['data']['return']['minions']
43 minions_pre = content['return'][0]['data']['return']['minions_pr e']
44 return minions,minions_pre
45
46 def delete_key(self,node_name):
47 params = {'client': 'wheel', 'fun': 'key.delete', 'match': node_ name}
48 obj = urllib.urlencode(params)
49 self.token_id()
50 content = self.postRequest(obj)
51 ret = content['return'][0]['data']['success']
52 return ret
53
54 def accept_key(self,node_name):
55 params = {'client': 'wheel', 'fun': 'key.accept', 'match': node_ name}
56 obj = urllib.urlencode(params)
57 self.token_id()
58 content = self.postRequest(obj)
59 ret = content['return'][0]['data']['success']
60 return ret
61
62 def remote_noarg_execution(self,tgt,fun):
63 ''' Execute commands without parameters '''
64 params = {'client': 'local', 'tgt': tgt, 'fun': fun}
65 obj = urllib.urlencode(params)
66 self.token_id()
67 content = self.postRequest(obj)
68 ret = content['return'][0][tgt]
69 return ret
70
71 def remote_execution(self,tgt,fun,arg):
72 ''' Command execution with parameters '''
73 params = {'client': 'local', 'tgt': tgt, 'fun': fun, 'arg': arg}
74 obj = urllib.urlencode(params)
75 self.token_id()
76 content = self.postRequest(obj)
77 ret = content['return'][0][tgt]
78 return ret
79
80 def target_remote_execution(self,tgt,fun,arg):
81 ''' Use targeting for remote execution '''
82 params = {'client': 'local', 'tgt': tgt, 'fun': fun, 'arg': arg, 'expr_form': 'nodegroup'}
83 obj = urllib.urlencode(params)
84 self.token_id()
85 content = self.postRequest(obj)
86 jid = content['return'][0]['jid']
87 return jid
88
89 def deploy(self,tgt,arg):
90 ''' Module deployment '''
91 params = {'client': 'local', 'tgt': tgt, 'fun': 'state.sls', 'ar g': arg}
92 obj = urllib.urlencode(params)
93 self.token_id()
94 content = self.postRequest(obj)
95 return content
96
97 def async_deploy(self,tgt,arg):
98 ''' Asynchronously send a command to connected minions '''
99 params = {'client': 'local_async', 'tgt': tgt, 'fun': 'state.sls ', 'arg': arg}
100 obj = urllib.urlencode(params)
101 self.token_id()
102 content = self.postRequest(obj)
103 jid = content['return'][0]['jid']
104 return jid
105
106 def target_deploy(self,tgt,arg):
107 ''' Based on the node group forms deployment '''
108 params = {'client': 'local_async', 'tgt': tgt, 'fun': 'state.sls ', 'arg': arg, 'expr_form': 'nodegroup'}
109 obj = urllib.urlencode(params)
110 self.token_id()
111 content = self.postRequest(obj)
112 jid = content['return'][0]['jid']
113 return jid
114
115 def main():
116 sapi = SaltAPI(url='https://172.25.44.5:8000',username='saltapi',pas sword='westos')
117 #sapi.token_id()
118 #print sapi.list_all_key()
119 #sapi.delete_key('test-01')
120 #sapi.accept_key('test-01')
121 sapi.deploy('server7','nginx.service')
122 #print sapi.remote_noarg_execution('test-01','grains.items')
123
124 if __name__ == '__main__':
125 main()
[root@server5 master.d]# python salt-api.py #执行脚本
[root@server7 ~]# ps ax #通过调用脚本启动nginx