consul在使用或测试中过程中,可能会产生不少垃圾数据(不健康的服务,没有完成注销动作而遗留在consul内),手动清理比较麻烦,然后自己写了个python脚本来一键清理这些脏数据,分享给大家。

脚本:consul_purge.py

环境依赖:python2、3

包依赖:pip install python-consul

#!/usr/bin/env python# -*- coding: utf-8 -*-# consul unhealth service purge script__author__ = 'whyvv blog'import consulimport sysimport getopt# define variablesconsul_address = '127.0.0.1'consul_port = '8500'consul_dc = ''usage = '''Usage: purge_unhealth_service.py -h  -p  -d help: -H,--host consul host address(default:127.0.0.1) -p,--port consul port(default:8500) -d,--datacenter consul datacenter(default:null) -h,--help Usage help'''# purge unhealth service for consuldef purge_unhealth_service(server=consul_address, server_port=consul_port, consul_dc=consul_dc): consul_obj = consul.Consul(host=server, port=server_port, scheme='http', dc=consul_dc) all_services = consul_obj.health.state('any') for service in all_services[1]: if service['Status'] != 'passing': print('purge %s "%s" Service with ServiceID: "%s" on Node %s' % (service['Status'], service['ServiceName'], service['ServiceID'], service['Node'])) p_consul_obj = consul.Consul(host=service['Node'], port=server_port, scheme='http', dc=consul_dc) pruge_rc = p_consul_obj.agent.service.deregister(service['ServiceID']) if pruge_rc: print('purge successful!') else: print('purge failed!') if __name__ == '__main__': # get args if sys.argv[1:]: opts, args = getopt.getopt(sys.argv[1:], 'hH:p:d:', ['help', 'host=', 'port=', 'datacenter=']) for opt, arg in opts: if opt in ('-H', '--host'): consul_address = arg elif opt in ('-p', '--port'): consul_port = int(arg) elif opt in ('-d', '--datacenter'): consul_dc = arg else: print(usage) exit() purge_unhealth_service()

使用帮助:./purge_unhealth_service.py --help

注:此脚本会清理所有非passing(健康)状态的服务,请谨慎使用!

b442c180a53f81edf7b4150eeba24ada.png
Logo

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。

更多推荐