SaltStack--API调用

API调用

利用api接口来实现SaltStack推送,管理集群是非常方便的手段

1.在server1上安装salt api

[root@server1 ~]# yum install -y salt-api-2018.3.3-1.el7.noarch.rpm

2.配置自签名证书

[root@server1 private]# pwd
/etc/pki/tls/private
[root@server1 private]# openssl genrsa 1024
[root@server1 private]# openssl genrsa 1024 > localhost.key
localhost.key
[root@server1 private]# ll
total 8
-rw-r--r-- 1 root root 887 Jun 19 10:32 localhost.key			##要有读的权限
-rw-r--r-- 1 root root 887 Jun 19 10:05 local.key


[root@server1 private]# cd ../certs
[root@server1  certs]# make testcert

SaltStack--API调用_第1张图片

SaltStack--API调用_第2张图片

3.编辑api.conf和auth.conf

[root@server1 certs]# vim /etc/salt/master #只支持以.conf结尾的文件

[root@server1 certs]# cd /etc/salt/master.d/
[root@server1 master.d]# vim api.conf
[root@server1 master.d]# cat api.conf 
rest_cherrypy:
  port: 8000
  ssl_crt: /etc/pki/tls/certs/localhost.crt
  ssl_key: /etc/pki/tls/private/localhost.key

[root@server1 master.d]# vim auth.conf
[root@server1 master.d]# cat auth.conf 
external_auth:
  pam:
    saltapi:
      - .*
      - '@wheel'
      - '@runner'
      - '@jobs'

在这里插入图片描述

4.创建用户并设置密码

[root@server1 master.d]# useradd saltapi
[root@server1 master.d]# passwd saltapi				##密码为redhat
Changing password for user saltapi.
New password: 
BAD PASSWORD: The password is shorter than 8 characters
Retype new password: 
passwd: all authentication tokens updated successfully.

5.打开salt-api,重启salt-master,并查看是否监听8000端口

[root@server1 master.d]# systemctl start salt-api
[root@server1 master.d]# systemctl restart salt-master
[root@server1 master.d]# netstat -antlp | grep 8000
tcp        0      0 0.0.0.0:8000            0.0.0.0:*               LISTEN      15435/salt-api

6.验证服务并获得token

[root@server1 master.d]# curl -sSk https://localhost:8000/login -d username=saltapi -d password=redhat -d eauth=pam
{"return": [{"perms": [".*", "@wheel", "@runner", "@jobs"], "start": 1560912154.411231, "token": "8c49fd8495c432cfa81f3

在这里插入图片描述

7.利用token号测试minion是否通

[root@server1 master.d]# curl -sSk https://localhost:8000 -H 'Accept: application/x-yaml' -H 'X-Auth-Token: b67576688061ab7e70de50c082933f60790fcc1c' -d client=local -d tgt='*' -d fun=test.ping 
return:
- server2: true
  server3: true

在这里插入图片描述

8.编写saltapi的python脚本

[root@server1 ~]# vim saltapi.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.68.1:8000",username="saltapi",password="westos")
    #sapi.token_id()
    print sapi.list_all_key()
    #sapi.delete_key('test-01')
    #sapi.accept_key('test-01')
    sapi.deploy('server2','apache.install')
    #print sapi.remote_noarg_execution('test-01','grains.items')
    
if __name__ == '__main__':
    main()

9.使用python执行脚本

server2先关闭httpd,server1执行saltapi.py脚本后,server2的httpd服务开启

[root@server2 salt]# systemctl stop httpd
[root@server1 ~]# python saltapi.py 
([u'server2', u'server3'], [])

在这里插入图片描述

SaltStack--API调用_第3张图片

你可能感兴趣的:(SaltStack--API调用)