這點時間研究運維自動化,研究到salt-api部分遇到了很多坑,這裡記錄一下,前面的陸續補上。
1、程序正題,步驟開始:
<code>cd /etc/yum.repos.d/ && wget http:</code><code>//dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm</code>
<code>rpm -ivh epel-release-</code><code>6</code><code>-</code><code>8</code><code>.noarch.rpm</code>
<code>yum -y install kernel-firmware kernel-headers perf e2fsprogs</code>
<code>rpm -ivh libyaml-</code><code>0.1</code><code>.</code><code>3</code><code>-</code><code>1.4</code><code>.el6.x86_64.rpm </code>
<code>rpm -ivh PyYAML-</code><code>3.10</code><code>-</code><code>3.1</code><code>.el6.x86_64.rpm </code>
<code>yum -y install salt-master salt-api </code>
2、
<code>#安裝pip:</code>
<code>wget https:</code><code>//pypi.python.org/packages/source/p/pip/pip-1.5.6.tar.gz#md5=01026f87978932060cc86c1dc527903e --no-check-certificate</code>
<code>tar xvfz pip-</code><code>1.5</code><code>.</code><code>6</code><code>.tar.gz</code>
<code>cd pip-</code><code>1.5</code><code>.</code><code>6</code>
<code>python setup.py build && python setup.py install && pip freeze</code>
<code>#使用pip安裝cherrypy:</code>
<code>pip install cherrypy==</code><code>3.2</code><code>.</code><code>3</code>
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: #再次輸入
/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
<code>#salt master配置檔案:/etc/salt/master </code>
<code>#取消注釋</code>
<code>default_include: master.d/*.conf</code>
<code>mkdir -p /etc/salt/master.d</code>
<code>#saltstack服務端配置:</code>
<code>[root@localhost ~]# cat /etc/salt/master.d/api.conf </code>
<code>rest_cherrypy:</code>
<code> </code><code>port: </code><code>8888</code>
<code> </code><code>ssl_crt: /etc/pki/tls/certs/localhost.crt</code>
<code> </code><code>ssl_key: /etc/pki/tls/</code><code>private</code><code>/localhost_nopass.key</code>
<code>[root@localhost ~]# cat /etc/salt/master.d/eauth.conf </code>
<code>external_auth:</code>
<code> </code><code>pam:</code>
<code> </code><code>xiaoluo:</code>
<code> </code><code>- .*</code>
<code> </code><code>- </code><code>'@wheel'</code>
<code> </code><code>- </code><code>'@runner'</code>
<code> </code>
<code>#重新開機salt-master和salt-api服務: </code>
<code>[root@mail ~]# /etc/init.d/salt-master restart</code>
<code>Stopping salt-master daemon: [FAILED]</code>
<code>Starting salt-master daemon: [ OK ]</code>
登入擷取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'
- 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}
ret = content['return'][0]['data']['success']
return ret
def accept_key(self,node_name):
params = {'client': 'wheel', 'fun': 'key.accept', 'match': node_name}
def remote_noarg_execution(self,tgt,fun):
''' Execute commands without parameters '''
params = {'client': 'local', 'tgt': tgt, 'fun': fun}
ret = content['return'][0]['monitor']['cpu_model']
def remote_execution(self,tgt,fun,arg):
''' Command execution with parameters '''
params = {'client': 'local', 'tgt': tgt, 'fun': fun, 'arg': arg}
ret = content['return'][0][tgt]
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'}
jid = content['return'][0]['jid']
return jid
def deploy(self,tgt,arg):
''' Module deployment '''
params = {'client': 'local', 'tgt': tgt, 'fun': 'state.sls', 'arg': arg}
def async_deploy(self,tgt,arg):
''' Asynchronously send a command to connected minions '''
params = {'client': 'local_async', 'tgt': tgt, 'fun': 'state.sls', 'arg': arg}
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'}
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
本文轉自 小羅ge11 51CTO部落格,原文連結:http://blog.51cto.com/xiaoluoge/1613353,如需轉載請自行聯系原作者