#!/usr/bin/env python
# -*- coding: utf8 -*-
import os
import re
import json
import urllib
import urllib2
#import jsonpath
#import requests
host = '10.***.***.***'
port = '8500'
#consul中微服务名称
serviceNames='xxx-xxx-server';
def get_service():
url = 'http://'+host+':'+port+'/v1/agent/services';
jsonStr = urllib2.urlopen(url)
data = json.load(jsonStr)
print(data)
serviceArray=re.findall(r"'Service': '([a-zA-Z0-9-]+)'", str(data).replace("u'","'"))
idArray=re.findall(r"'ID': '([a-zA-Z0-9-]+)'", str(data).replace("u'","'"))
print(serviceArray)
print(idArray)
for i in range(len(serviceArray)):
if serviceNames == serviceArray[i]:
del_service(idArray[i])
def del_service(keys):
url2 = 'http://'+host+':'+str(port)+'/v1/agent/service/deregister/'+keys
req=urllib2.Request(url2)
req.get_method = lambda: 'PUT'
ret = urllib2.urlopen(req).read()
if __name__ == '__main__':
get_service()
基于python2.7开发,由于容器部署的服务每次部署IP会发生变化,因此每次动态获取已经存注册在consul上的ID,进行注销