Consul Template 是 HashiCorp 生态中用于自动替换配置文件的利器,它能根据 Consul 中的服务发现数据动态渲染本地文件。
快速上手
先搞定环境,从官方发布页下载对应系统的二进制包:
wget https://releases.hashicorp.com/consul-template/0.25.0/consul-template_0.25.0_linux_amd64.zip
unzip consul-template_0.25.0_linux_amd64.zip
mv consul-template /usr/local/bin/
验证安装是否成功:
consul-template -v
# 输出示例:consul-template v0.25.0
环境准备
为了演示效果,我们先启动一个开发模式的 Consul 集群:
consul agent -dev -ui -client 0.0.0.0
配置模板
接下来创建配置文件 tmpl.json,定义数据源和输出目标:
{
"consul": "127.0.0.1:8500",
"template": {
"source": "./print1.ctmpl",
"destination": "./print1.py",
"command": "python ./print1.py"
}
}
注意上面的 template 块,它告诉工具去读取 print1.ctmpl,生成 print1.py,并在生成后自动执行该脚本。
编写模板
模板文件支持 Go 的 text/template 语法。这里我们写一个简单的 Python 脚本来打印服务列表:
#!/usr/bin/python
#coding:utf-8
iplist = [ {{range service "hello"}} "{{.Address}}",{{end}} ]
port = 8080
for ip iplist:
ip

