我在使用consul的时候主要用于prometheus的consul服务发现,把数据库、虚拟机信息发布到consul,prometheus通过consul拿到数据库、虚拟机信息去采集指标信息。
此篇文章前提是已经安装好consul服务以后,安装consul请参考二进制方式部署consul单机版进行安装。
1.consul模板
文件名:consul-register.json.template
{
"ID": "{{ exporter_id }}",
"Name": "{{ exporter_id }}",
"Tags": [
{% for tag in tags %}
"{{ tag }}"{% if not loop.last %},{% endif %}
{% endfor %}
],
"Address": "{{ exporter_address }}",
"Port": {{ exporter_port }},
"Meta": {
{% for key, value in labels.items() %}
"{{ key }}":"{{ value }}"{% if not loop.last %},{% endif %}
{% endfor %}
},
"EnableTagOverride": false,
"Weights": {
"Passing": 10,
"Warning": 1
}
}
2.consul服务注册
import json
import os
import requests
from jinja2 import Environment, FileSystemLoader
class Config:
PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
# 配置文件地址,根据自身存放路径修改
CONSUL_TEMPLATE_DIR = os.path.join(PROJECT_DIR, 'common/consul')
jinja_env = Environment(loader=FileSystemLoader(Config.CONSUL_TEMPLATE_DIR))
consul_register_template = jinja_env.get_template('consul-register.json.template')
def register_vhost_exporter_to_consul() -> None:
print(f"register node exporter to consul.")
host = "192.168.56.108"
exporter_id = f'node-exporter-192.168.56.108'
params = consul_register_template \
.render(exporter_id=exporter_id,
tags=['vhost', 'node', 'exporter', 'node-exporter'],
exporter_address=host,
exporter_port=49150,
labels={
"host": host,
"bk_inst_id": 1,
"vh_oper_staff": 'test'
})
print(f"Start register svc: {exporter_id}")
# http://192.168.56.108:8500为consul服务器地址
resp = requests.put(f"http://192.168.56.108:8500/v1/agent/service/register",
json=json.loads(params),
verify=False)
if not resp.ok:
raise Exception(f"register svc {exporter_id} failed.")
print(f"register svc {exporter_id} Success.")
if __name__ == '__main__':
register_vhost_exporter_to_consul()
执行注册后,效果如下图
3.consul服务注销
import requests
def unregister_vhost_exporter_from_consul():
exporter_id = f'node-exporter-192.168.56.108'
resp = requests.put(f"http://192.168.56.108:8500/v1/agent/service/deregister/{exporter_id}",
verify=False)
if not resp.ok and resp.status_code != 404:
# 404说明已经取消注册过了
raise Exception(f"unregister svc {exporter_id} failed.")
if __name__ == '__main__':
unregister_vhost_exporter_from_consul()
注销后效果如下图