利用api接口来实现SaltStack推送,管理集群是非常方便的手段,下面我们尝试利用API来实现Salt的功能
如果server2和server3没有开启salt-minion服务,请先开启
1.在server1安装salt-api服务
[root@server1 master.d]# yum install -y salt-api
2.配置签名证书
[root@server1 tls]# cd private/
[root@server1 private]# ls
[root@server1 private]# openssl genrsa 2048
[root@server1 private]# openssl genrsa 2048 > localhost.key
[root@server1 private]# ls
localhost.key
[root@server1 private]# md5sum localhost.key
a45eec69648e2d4b4168b3bdf675d771 localhost.key
[root@server1 tls]# cd certs/
[root@server1 certs]# ls
ca-bundle.crt make-dummy-cert renew-dummy-cert
ca-bundle.trust.crt Makefile
[root@server1 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]:redgat
Organizational Unit Name (eg, section) []:linux
Common Name (eg, your name or your server's hostname) []:server1
Email Address []:root@localhost
[root@server1 certs]# ls
ca-bundle.crt localhost.crt Makefile
ca-bundle.trust.crt make-dummy-cert renew-dummy-cert
3.编辑api.conf和auth.conf
[root@server1 private]# cd /etc/salt/master.d/
[root@server1 master.d]# ls
[root@server1 master.d]# vim 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]# useradd saltapi
[root@server1 master.d]# passwd saltapi
[root@server1 master.d]# vim auth.conf
external_auth:
pam:
saltapi:
- .*
- '@wheel' # to allow access to all wheel modules
- '@runner'
- '@jobs'
4.打开salt-api,重启salt-master,并查看是否监听8000端口
[root@server1 master.d]# systemctl restart salt-master
[root@server1 master.d]# systemctl start salt-api
[root@server1 master.d]# ls
api.conf auth.conf
[root@server1 master.d]# netstat -ntlp
tcp 0 0 0.0.0.0:8000 0.0.0.0:* LISTEN 10915/salt-api
5.登陆服务并获得token
[root@server1 master.d]# curl -sSk https://localhost:8000/login \ #登陆获取token值
> -H 'Accept: application/x-yaml' \
> -d username=saltapi \
> -d password=redhat -d eauth=pam
return:
- eauth: pam
expire: 1565793955.933131
perms:
- .*
- '@wheel'
- '@runner'
- '@jobs'
start: 1565750755.933129
token: ac667b5b9f061d27ee0247c2608b3c35774c6018
user: saltapi
6.利用token号测试
[root@server1 master.d]# curl -sSk https://localhost:8000/ -H 'Accept: application/x-yaml' -H 'X-Auth-Token: ac667b5b9f061d27ee0247c2608b3c35774c6018' -d client=local -d tgt='*' -d fun=test.ping
7.配置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://localhost:8000',username='saliapi',password='redhat')
#sapi.token_id()
print sapi.list_all_key() #列出所有节点
#sapi.delete_key('test-01')
#sapi.accept_key('test-01')
sapi.deploy('server2','apache.install') #server2安装httpd,这需要我们之前在server1上配置saltstack一键化部署httpd服务的install.sls相关文件
#print sapi.remote_noarg_execution('test-01','grains.items')
if __name__ == '__main__':
main()
[root@server1 ~]# systemctl restart salt-master
[root@server1 ~]# systemctl restart salt-api
[root@server2 ~]# systemctl stop httpd #关闭httpd做测试
[root@server1 ~]# python saltapi.py
([u’server2’, u’server3’], [])
server2查看:
[root@server2 ~]# ps ax