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"


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM