saltstack自动运维工具--与mysql的结合,salt-ssh连接操作,salt-syndic模块,salt-api调用

将推送操作返回到数据库

在server5(master)中:

yum install mysql-server -y
[root@server5 files]# /etc/init.d/mysqld start
[root@server5 ~]# vim test.sql  ###将17行注释掉
[root@server5 ~]# mysql < test.sql  ##导入数据库
CREATE DATABASE  `salt`
  DEFAULT CHARACTER SET utf8
  DEFAULT COLLATE utf8_general_ci;

USE `salt`;

--
-- 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;

--
-- 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;

--
-- 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`)
[root@server5 ~]# mysql
mysql> grant all on salt.* to salt@'172.25.3.%' identified by 'westos';

在server4(minimo)端

vim /etc/salt/minion
修改其配置文件
814 mysql.host: '172.25.3.5'
815 mysql.user: 'salt'
816 mysql.pass: 'westos'
817 mysql.db: 'salt'
818 mysql.port: 3306

saltstack自动运维工具--与mysql的结合,salt-ssh连接操作,salt-syndic模块,salt-api调用_第1张图片

[root@server5 ~]# salt 'server4' test.ping --return mysql
server4:
    True
 [root@server5 ~]# mysql
mysql> use salt
mysql> select * from salt_returns;

saltstack自动运维工具--与mysql的结合,salt-ssh连接操作,salt-syndic模块,salt-api调用_第2张图片
第二种模式:
在server5(master)中:

[root@server5 ~]# yum install MySQL-python.x86_64 -y
[root@server5 salt]# vim master
[root@server5 salt]# /etc/init.d/salt-master restart

修改master文件内容如下:

 143 master_job_cache: mysql
 144 mysql.host: 'localhost'  ###定义主机名
 145 mysql.user: 'salt'  ###定义用户
 146 mysql.pass: 'westos'  ##定义密码
 147 mysql.db: 'salt'   
 148 mysql.port: 3306

saltstack自动运维工具--与mysql的结合,salt-ssh连接操作,salt-syndic模块,salt-api调用_第3张图片

[root@server5 ~]# mysql
mysql> grant all on salt.* to salt@localhost identified by 'westos';
[root@server5 ~]# salt 'server4' test.ping --return mysql 
server4:   ##推送,将其返回到数据库
    True
[root@server5 ~]# mysql
mysql> use salt
mysql> select * from salt_returns;  ###查看返回信息

saltstack自动运维工具--与mysql的结合,salt-ssh连接操作,salt-syndic模块,salt-api调用_第4张图片


[root@server5 ~]# mkdir /srv/salt/_modules  ##建立python函数模块
[root@server5 ~]# cd /srv/salt/_modules
[root@server5 _modules]# vim my_disk.py
#!/usr/bin/env  python
def df():
    return _salt_['cmd.run']('df -h')

saltstack自动运维工具--与mysql的结合,salt-ssh连接操作,salt-syndic模块,salt-api调用_第5张图片

[root@server5 _modules]# salt '*' saltutil.sync_modules
###同步模块数据

saltstack自动运维工具--与mysql的结合,salt-ssh连接操作,salt-syndic模块,salt-api调用_第6张图片

[root@server5 _modules]# salt '*' my_disk.df
##调用模块函数

saltstack自动运维工具--与mysql的结合,salt-ssh连接操作,salt-syndic模块,salt-api调用_第7张图片

salt-syndic模块

在server5上(原来的master):

[root@server5 ~]# salt-key -d server7
###去掉server7这个节点
[root@server5 ~]# salt-key -L
###查看是否去除

saltstack自动运维工具--与mysql的结合,salt-ssh连接操作,salt-syndic模块,salt-api调用_第8张图片
在server7(top-master)上:

[root@server7 haproxy]# /etc/init.d/salt-minion stop
[root@server7 haproxy]# chkconfig salt-minion off
[root@server7 haproxy]# /etc/init.d/haproxy stop
[root@server7 haproxy]# /etc/init.d/keepalived stop

[root@server7 haproxy]# yum install -y salt-master
[root@server7 ~]# vim /etc/salt/master
[root@server7 ~]# /etc/init.d/salt-master start

saltstack自动运维工具--与mysql的结合,salt-ssh连接操作,salt-syndic模块,salt-api调用_第9张图片
在server5上(原来的master):

[root@server5 ~]# yum install -y salt-syndic
[root@server5 ~]# /etc/init.d/salt-syndic start

[root@server5 ~]# vim /etc/salt/master
[root@server5 ~]# /etc/init.d/salt-master start

编辑master配置文件:
saltstack自动运维工具--与mysql的结合,salt-ssh连接操作,salt-syndic模块,salt-api调用_第10张图片
在server7上:

[root@server7 ~]# salt-key -L  ##查看节点
Accepted Keys:
Denied Keys:
Unaccepted Keys:
server5
Rejected Keys:
[root@server7 ~]# salt-key -A  ##添加节点

saltstack自动运维工具--与mysql的结合,salt-ssh连接操作,salt-syndic模块,salt-api调用_第11张图片

[root@server7 ~]# salt '*' test.ping
执行,会发现看到其它节点,topmaster实际上看的时server5的master

saltstack自动运维工具--与mysql的结合,salt-ssh连接操作,salt-syndic模块,salt-api调用_第12张图片

salt-ssh连接操作
[root@server5 ~]# yum install salt-ssh -y
[root@server5 ~]# vim /etc/salt/roster

saltstack自动运维工具--与mysql的结合,salt-ssh连接操作,salt-syndic模块,salt-api调用_第13张图片

[root@server5 ~]# vim /etc/salt/master
###将之前写的数据库的模块注释掉

saltstack自动运维工具--与mysql的结合,salt-ssh连接操作,salt-syndic模块,salt-api调用_第14张图片
关闭server6的minion,通过ssh连接,成功
saltstack自动运维工具--与mysql的结合,salt-ssh连接操作,salt-syndic模块,salt-api调用_第15张图片

salt-api调用

[root@server5 ~]# yum install salt-api -y
[root@server5 ~]# cd /etc/pki/
[root@server5 pki]# ls
CA  ca-trust  entitlement  java  nssdb  product  rpm-gpg  rsyslog  tls
[root@server5 pki]# cd tls/private/
[root@server5 private]# ls
[root@server5 private]# openssl genrsa 1024

saltstack自动运维工具--与mysql的结合,salt-ssh连接操作,salt-syndic模块,salt-api调用_第16张图片

[root@server5 private]# openssl genrsa 1024 > localhost.key
Generating RSA private key, 1024 bit long modulus
.......++++++
...............................................++++++
e is 65537 (0x10001)

saltstack自动运维工具--与mysql的结合,salt-ssh连接操作,salt-syndic模块,salt-api调用_第17张图片

[root@server5 tls]# cd certs/
[root@server5 certs]# make testcert

saltstack自动运维工具--与mysql的结合,salt-ssh连接操作,salt-syndic模块,salt-api调用_第18张图片

[root@server5 certs]# cd /etc/salt/
[root@server5 salt]# cd master.d/
[root@server5 master.d]# pwd
/etc/salt/master.d
[root@server5 master.d]# vim api.conf  ###写api调用文件
rest_cherrypy:
  port: 8000
  ssl_crt: /etc/pki/tls/certs/localhost.crt
  ssl_key: /etc/pki/tls/private/localhost.key

saltstack自动运维工具--与mysql的结合,salt-ssh连接操作,salt-syndic模块,salt-api调用_第19张图片

[root@server5 master.d]# vim auth.conf  ###写认证文件
external_auth:
  pam:
    saltapi:
      - '.*'
      - '@wheel'
      - '@runner'
      - '@jobs'
[root@server5 master.d]# useradd saltapi  ##建立用户
[root@server5 master.d]# passwd saltapi   ###设置用户密码

saltstack自动运维工具--与mysql的结合,salt-ssh连接操作,salt-syndic模块,salt-api调用_第20张图片

[root@server5 master.d]# /etc/init.d/salt-master stop
Stopping salt-master daemon:                               [  OK  ]
[root@server5 master.d]# /etc/init.d/salt-master status
salt-master is stopped
[root@server5 master.d]# /etc/init.d/salt-master start
Starting salt-master daemon:                               [  OK  ]
[root@server5 master.d]# /etc/init.d/salt-api start
Starting salt-api daemon:                                  [  OK  ]
[root@server5 master.d]# netstat -antlp | grep :8000
tcp        0      0 0.0.0.0:8000                0.0.0.0:*                   LISTEN      6902/python2.6      
tcp        0      0 127.0.0.1:53571             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

saltstack自动运维工具--与mysql的结合,salt-ssh连接操作,salt-syndic模块,salt-api调用_第21张图片

[root@server5 master.d]# curl -sSk https://localhost:8000 \
> -H 'Accept: application/x-yaml' \
> ###这里的token为上面步骤获取的
> -H 'X-Auth-Token:4345d302c757e6e5039cd7eb49413770172ae17c' \
> -d client=local \
> -d tgt='*' \
> -d fun=test.ping

saltstack自动运维工具--与mysql的结合,salt-ssh连接操作,salt-syndic模块,salt-api调用_第22张图片
编辑一个salt-api.py

# -*- coding: utf-8 -*-

import urllib2,urllib
import time

try:
    import json
except ImportError:
    import simplejson as json

class SaltAPI(object):
    __token_id = ''
    def __init__(self,url,username,password):
        self.__url = url.rstrip('/')
        self.__user = username
        self.__password = password

    def token_id(self):
        ''' user login and get token id '''
        params = {'eauth': 'pam', 'username': self.__user, 'password': self.__password}
        encode = urllib.urlencode(params)
        obj = urllib.unquote(encode)
        content = self.postRequest(obj,prefix='/login')
    try:
            self.__token_id = content['return'][0]['token']
        except KeyError:
            raise KeyError

    def postRequest(self,obj,prefix='/'):
        url = self.__url + prefix
        headers = {'X-Auth-Token'   : self.__token_id}
        req = urllib2.Request(url, obj, headers)
        opener = urllib2.urlopen(req)
        content = json.loads(opener.read())
        return content

    def list_all_key(self):
        params = {'client': 'wheel', 'fun': 'key.list_all'}
        obj = urllib.urlencode(params)
        self.token_id()
        content = self.postRequest(obj)
        minions = content['return'][0]['data']['return']['minions']
        minions_pre = content['return'][0]['data']['return']['minions_pre']
        return minions,minions_pre

    def delete_key(self,node_name):
        params = {'client': 'wheel', 'fun': 'key.delete', 'match': node_name}
        obj = urllib.urlencode(params)
        self.token_id()
        content = self.postRequest(obj)
        ret = content['return'][0]['data']['success']
        return ret

    def accept_key(self,node_name):
        params = {'client': 'wheel', 'fun': 'key.accept', 'match': node_name}
        obj = urllib.urlencode(params)
        self.token_id()
        content = self.postRequest(obj)
        ret = content['return'][0]['data']['success']
        return ret

    def remote_noarg_execution(self,tgt,fun):
        ''' Execute commands without parameters '''
        params = {'client': 'local', 'tgt': tgt, 'fun': fun}
        obj = urllib.urlencode(params)
        self.token_id()
        content = self.postRequest(obj)
        ret = content['return'][0][tgt]
        return ret

    def remote_execution(self,tgt,fun,arg):
        ''' Command execution with parameters '''        
        params = {'client': 'local', 'tgt': tgt, 'fun': fun, 'arg': arg}
        obj = urllib.urlencode(params)
        self.token_id()
        content = self.postRequest(obj)
        ret = content['return'][0][tgt]
        return ret

    def target_remote_execution(self,tgt,fun,arg):
        ''' Use targeting for remote execution '''
        params = {'client': 'local', 'tgt': tgt, 'fun': fun, 'arg': arg, 'expr_form': 'nodegroup'}
        obj = urllib.urlencode(params)
        self.token_id()
        content = self.postRequest(obj)
        jid = content['return'][0]['jid']
        return jid

    def deploy(self,tgt,arg):
        ''' Module deployment '''
        params = {'client': 'local', 'tgt': tgt, 'fun': 'state.sls', 'arg': arg}
        obj = urllib.urlencode(params)
        self.token_id()
        content = self.postRequest(obj)
        return content

    def async_deploy(self,tgt,arg):
        ''' Asynchronously send a command to connected minions '''
        params = {'client': 'local_async', 'tgt': tgt, 'fun': 'state.sls', 'arg': arg}
        obj = urllib.urlencode(params)
        self.token_id()
        content = self.postRequest(obj)
        jid = content['return'][0]['jid']
        return jid

    def target_deploy(self,tgt,arg):
        ''' Based on the node group forms deployment '''
        params = {'client': 'local_async', 'tgt': tgt, 'fun': 'state.sls', 'arg': arg, 'expr_form': 'nodegroup'}
        obj = urllib.urlencode(params)
        self.token_id()
        content = self.postRequest(obj)
        jid = content['return'][0]['jid']
        return jid

def main():
    sapi = SaltAPI(url='https://172.25.3.5:8000',username='saltapi',password='westos')
    sapi.token_id()
    #print sapi.list_all_key()  ##将这行显示key值的注释掉
    #sapi.delete_key('test-01')
    #sapi.accept_key('test-01')
    sapi.deploy('server6','nginx.service')  
    ###开启调用server6的nginx服务
    #print sapi.remote_noarg_execution('test-01','grains.items')

if __name__ == '__main__':
    main()

saltstack自动运维工具--与mysql的结合,salt-ssh连接操作,salt-syndic模块,salt-api调用_第23张图片
在server6上关闭nginx
这里写图片描述

[root@server5 ~]# python salt-api.py 
###调用python脚本,在server6中ps ax查看服务已开启

这里写图片描述

你可能感兴趣的:(saltstack自动运维工具--与mysql的结合,salt-ssh连接操作,salt-syndic模块,salt-api调用)