Consul Template的简单使用

Consul Template的使用


1安装

地址 https://github.com/hashicorp/consul-template/releases

wget https://releases.hashicorp.com/consul-template/0.14.0/consul-template_0.14.0_linux_amd64.zip

unzip consul-template_0.14.0_linux_amd64.zip cp consul-template /usr/local/bin

2 执行命令前 请确定已经安装consul 并且创建好了集群

3 创建模板

tmpltest.ctmpl

内容

{{range services}}
{{.Name}}
{{range .Tags}}
{{.}}{{end}}
{{end}}

4 执行

E:consul321>consul-template.exe -consul 192.168.5.156:8500 -template "./tmpl/tmpltest.ctmpl:./tmpl/result"

命令说明:
-consul后是consul的webui接口 ,用web管理consul就用的8500端口。

-template 后面是模板参数 第一个是模板地址 。冒号后的第二个参数是输出位置。

结果:

consul

sonarqube

dev

说明:consul 是系统自带的服务 sonarqube 是我创建的服务

该服务的配置文件sonarqube.json 内容如下

{
"service": {
"name": "sonarqube",
"tags": ["dev"],
"address":"www.163.com",
"port": 80,
"checks":[
{
"http":"http://www.163.com",
"interval":"5s"
}
]
}
}

其他

命令的其他参数和说明

-template 的参数 除了输入输出参数 还可以添加其他命令 如

E:consul321>consul-template.exe -consul 192.168.5.156:8500 -template "./tmpl/tmpltest.ctmpl:./tmpl/result:service nginx restart"

表示输出后 重启nginx服务

-config 模板配置文件的路径

-dry 模板内容不写入磁盘,写到控制台

-log-level 日志级别 通常是info warn之类

-max-stale 默认1秒,设置后,consul会把任务分发给各个server,而不是有leader独自完成。

-once 运行一次后退出

-pid-file 写模板文件的pid的信息保存的路径

-ssl 和consul使用ssl通信 相关的有ssl-ca-cert ssl-cert ssl-verify

-token consul的api token。没有默认值

-version 版本

除了consul和template 其他参数都是可选的

参看https://github.com/hashicorp/consul-template#examples

再来个例子
$ consul-template
-consul 127.0.0.1:8500
-template "/tmp/template.ctmpl:/var/www/nginx.conf:service nginx restart"
-retry 30s
-once
表示如果consul有问题的话,每30秒轮询一次。

来个证书的命令的例子

$ consul-template
-consul 127.0.0.1:8543
-ssl
-ssl-cert /path/to/client/cert.pem
-ssl-ca-cert /path/to/ca/cert.pem
-template "/tmp/template.ctmpl:/tmp/result"
-dry
-once

模板的配置文件

例如 创建一个tmpl.json文件
内容 如下

consul = "127.0.0.1:8500"

template {

source = "/etc/haproxy/haproxy.ctmpl"
destination = "/etc/haproxy/haproxy.cfg"
command = "service haproxy restart"

}
详细的参数可以看这里 https://github.com/hashicorp/consul-template#examples

接下来 我们就可以这样执行了
consul-template -config /data/cfg/consul/tmpl.json

如果有多个模板要执行的话,可以这样,配多个template参数就行了

consul-template
-consul my.consul.internal:6124
-template "/tmp/nginx.ctmpl:/var/nginx/nginx.conf:service nginx restart"
-template "/tmp/redis.ctmpl:/var/redis/redis.conf:service redis restart"
-template "/tmp/haproxy.ctmpl:/var/haproxy/haproxy.conf"

原文地址:https://www.cnblogs.com/wang2650/p/5526962.html