这点时间研究运维自动化,研究到salt-api部分遇到了很多坑,这里记录一下,前面的陆续补上。
1、进程正题,步骤开始:
cd /etc/yum.repos.d/ && wget http:
//dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
rpm -ivh epel-release-
6
-
8
.noarch.rpm
yum -y install kernel-firmware kernel-headers perf e2fsprogs
rpm -ivh libyaml-
0.1
.
3
-
1.4
.el6.x86_64.rpm
rpm -ivh PyYAML-
3.10
-
3.1
.el6.x86_64.rpm
yum -y install salt-master salt-api
2、
#安装pip:
wget https:
//pypi.python.org/packages/source/p/pip/pip-1.5.6.tar.gz#md5=01026f87978932060cc86c1dc527903e --no-check-certificate
tar xvfz pip-
1.5
.
6
.tar.gz
cd pip-
1.5
.
6
python setup.py build && python setup.py install && pip freeze
#使用pip安装cherrypy:
pip install cherrypy==
3.2
.
3
3、安装openssl证书,因为salt-api是基于证书的,目录不要给错:
[root@www tmp]# cd /etc/pki/tls/certs
[root@www certs]# make testcert
umask 77 ; \
/usr/bin/openssl genrsa -aes128 2048 > /etc/pki/tls/private/localhost.key
Generating RSA private key, 2048 bit long modulus
..............................................................................................................................................+++
........................................................+++
e is 65537 (0x10001)
Enter pass phrase: #输入6位以上的秘钥
Verifying - Enter pass phrase: #再次输入
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
Enter pass phrase for /etc/pki/tls/private/localhost.key: #再次输入
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) []:nanning
Locality Name (eg, city) [Default City]:ninning
Organization Name (eg, company) [Default Company Ltd]:
Organizational Unit Name (eg, section) []:
Common Name (eg, your name or your server's hostname) []:
Email Address []:[email protected]
[root@www certs]# cd ../private/
[root@www private]# openssl rsa -in localhost.key -out localhost_nopass.key
Enter pass phrase for localhost.key:
writing RSA key
建立登录的账号和密码:
[root@www private]# useradd -M -s /sbin/nologin xiaoluo
[root@www private]# passwd xiaoluo
#salt master配置文件:/etc/salt/master
#取消注释
default_include: master.d/*.conf
mkdir -p /etc/salt/master.d
#saltstack服务端配置:
[root@localhost ~]# cat /etc/salt/master.d/api.conf
rest_cherrypy:
port:
8888
ssl_crt: /etc/pki/tls/certs/localhost.crt
ssl_key: /etc/pki/tls/
private
/localhost_nopass.key
[root@localhost ~]# cat /etc/salt/master.d/eauth.conf
external_auth:
pam:
xiaoluo:
- .*
-
'@wheel'
-
'@runner'
#重启salt-master和salt-api服务:
[root@mail ~]# /etc/init.d/salt-master restart
Stopping salt-master daemon: [FAILED]
Starting salt-master daemon: [ OK ]
登录获取token:
[root@mail salt]# curl -k https://192.168.10.205:8888/login -H "Accept: application/x-yaml" -d username='xiaoluo' -d password='123456' -d eauth='pam'
return:
- eauth: pam
expire: 1423599495.7932329
perms:
- .*
- '@wheel'
- '@runner'
start: 1423556295.793232
token: 38fc58406d4248abded1abbfa11ce83b68754975
user: xiaoluo
获取token之后,可以使用token通信:
[root@mail salt]# curl -k https://192.168.10.205:8888/ -H "Accept: application/x-yaml" -H "X-Auth-Token: 38fc58406d4248abded1abbfa11ce83b68754975" -d client='local' -d tgt='*' -d fun='test.ping'
return:
- monitor: true
跟salt '*' test.ping的效果是一样的。这样就实现了salt-api接口的通信。
当然在开发获取数据的时候这样的办法显然是不够灵活的。下面贴出一个salt-api的类:
#!/usr/bin/env python
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]['monitor']['cpu_model']
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://192.168.10.205:8888',username='xiaoluo',password='123456')
print sapi.list_all_key()
# sapi.token_id()
#sapi.delete_key('test-01')
print sapi.accept_key('localhost')
#sapi.deploy('test-01','nginx')
print sapi.remote_noarg_execution('*','grains.items')
if __name__ == '__main__':
main()
##运行之后就会打印出grain的值。需要什么值可以直接打印。
测试效果:
[root@mail python]# python salt-api.py
([u'mail.shihuasuan.com', u'monitor'], [])
True
Intel(R) Xeon(R) CPU E5-2603 v2 @ 1.80GHz