本文共 2025 字,大约阅读时间需要 6 分钟。
一、首先要让salt-master找到我们自定义的脚本(/etc/salt/master):
使用ext_pillar 扩展自定义脚本,gameInfo就是脚本的名字,脚本的目录要放在/usr/lib/python2.6/site-packages/salt/pillar这个目录下面
新版可以支持自定义目录,使用参数extension_modules: /srv/salt/modules
二、自定义脚本需要返回字典数据,gameInfo脚本如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | #!/usr/bin/python #coding:utf-8 import urllib2 import json import logging # Set up logging log = logging.getLogger(__name__) def __virtual__(): return True def ext_pillar(minion_id, pillar, * args, * * kwargs): try : ip = minion_id.split( '-' )[ - 1 ] url = 'http://xxx.xxx.com/public/api/SaltPillarInfo/{ip}/' . format (ip = ip) request = urllib2.urlopen(url = url, timeout = 30 ) response = request.read() data = json.loads(response) logging.info( "From URL:{url} get data:{data}" . format (url = url, data = data)) except Exception as e: logging.error( str (e)) data = {} return { 'gameInfo' : data} |
因为我的minionid是'game-192.168.1.1' 这种用途-ip的形式命名,minion_id.split('-')[-1]获取出minion的IP,然后请求django提供的接口,将django返回的数据转换成python数据格式直接返回出来
三、django代码就很简单了
url配置
1 2 3 4 5 6 7 8 | from django.conf.urls import patterns, include, url from views import * urlpatterns = patterns('', url(r '^api/SaltPillarInfo/(?P<ip>.*)/$' , SaltPillarInfoApiView.as_view()), 以下省略。。。 ) |
views:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | class SaltPillarInfoApiView(View): def get( self , request, ip): try : hostobj = GameHost.objects.using( 'res' ).get(Q(ip1 = ip)|Q(ip2 = ip), state = 1 ) gamename = GameInfo.objects.using( 'res' ).get( id = hostobj.gameid).code plat = GamePlatform.objects.using( 'res' ).get( id = hostobj.platid).code serverlist = [ gsobj.serverid for gsobj in GameServer.objects.using( 'res' ). filter (hostid = hostobj. id , mergetarget__isnull = True ) ] ret = { 'gamename' : gamename, 'plat' : plat, 'serverlist' : serverlist } except Exception as e: print str (e) ret = {} return HttpResponse(json.dumps(ret)) |
直接请求就是这个效果啦:
四、测试:
妥妥地给机器打上游戏,平台,区服的标志了。。
本文转自运维笔记博客51CTO博客,原文链接http://blog.51cto.com/lihuipeng/1789433如需转载请自行联系原作者
lihuipeng