Consul-Template簡介
Consul-Template是基於Consul的自動替換配置文件的應用。在Consul-Template沒出現之前,大家構建服務發現系統大多采用的是Zookeeper、Etcd+Confd這樣類似的系統。
Consul官方推出了自己的模板系統Consul-Template后,動態的配置系統可以分化為Etcd+Confd和Consul+Consul-Template兩大陣營。Consul-Template的定位和Confd差不多,Confd的后端可以是Etcd或者Consul。
Consul-Template提供了一個便捷的方式從Consul中獲取存儲的值,Consul-Template守護進程會查詢Consul實例來更新系統上指定的任何模板。當更新完成后,模板還可以選擇運行一些任意的命令。
Consul-Template可以查詢Consul中的服務目錄、Key、Key-values等。這種強大的抽象功能和查詢語言模板可以使Consul-Template特別適合動態的創建配置文件。例如:創建Apache/Nginx Proxy Balancers、Haproxy Backends、Varnish Servers、Application Configurations等。
Consul-Template特性
- Quiescence:Consul-Template內置靜止平衡功能,可以智能的發現Consul實例中的更改信息。這個功能可以防止頻繁的更新模板而引起系統的波動。
- Dry Mode:不確定當前架構的狀態,擔心模板的變化會破壞子系統?無須擔心。因為Consul-Template還有Dry模式。在Dry模式,Consul-Template會將結果呈現在STDOUT,所以操作員可以檢查輸出是否正常,以決定更換模板是否安全。
- CLI and Config:Consul-Template同時支持命令行和配置文件。
- Verbose Debugging:即使每件事你都做的近乎完美,但是有時候還是會有失敗發生。Consul-Template可以提供更詳細的Debug日志信息。
項目地址:https://github.com/hashicorp/consul-template
Consul-Template安裝
Consul-Template和Consul一樣,也是用Golang實現。因此具有天然可移植性(支持 Linux、windows 和macOS)。安裝包僅包含一個可執行文件。Consul-Template安裝非常簡單,只需要下載對應系統的軟件包並解壓后就可使用。
這里以Linux系統為例:
1 $ wget https://releases.hashicorp.com/consul-template/0.18.3/consul-template_0.18.3_linux_amd64.zip 2 $ unzip consul-template_0.18.3_linux_amd64.zip 3 $ mv consul-template /usr/local/bin/
其它系統版本可在這里下載:https://releases.hashicorp.com/consul-template/
Consul-Template常用命令
1 $ consul-template -h 2 3 Usage: consul-template [options] 4 5 Watches a series of templates on the file system, writing new changes when 6 Consul is updated. It runs until an interrupt is received unless the -once 7 flag is specified. 8 9 Options: 10 11 -config=<path> 12 Sets the path to a configuration file or folder on disk. This can be 13 specified multiple times to load multiple files or folders. If multiple 14 values are given, they are merged left-to-right, and CLI arguments take 15 the top-most precedence. 16 17 -consul-addr=<address> 18 Sets the address of the Consul instance 19 20 -consul-auth=<username[:password]> 21 Set the basic authentication username and password for communicating 22 with Consul. 23 24 -consul-retry 25 Use retry logic when communication with Consul fails 26 27 -consul-retry-attempts=<int> 28 The number of attempts to use when retrying failed communications 29 30 -consul-retry-backoff=<duration> 31 The base amount to use for the backoff duration. This number will be 32 increased exponentially for each retry attempt. 33 34 -consul-ssl 35 Use SSL when connecting to Consul 36 37 -consul-ssl-ca-cert=<string> 38 Validate server certificate against this CA certificate file list 39 40 -consul-ssl-ca-path=<string> 41 Sets the path to the CA to use for TLS verification 42 43 -consul-ssl-cert=<string> 44 SSL client certificate to send to server 45 46 -consul-ssl-key=<string> 47 SSL/TLS private key for use in client authentication key exchange 48 49 -consul-ssl-server-name=<string> 50 Sets the name of the server to use when validating TLS. 51 52 -consul-ssl-verify 53 Verify certificates when connecting via SSL 54 55 -consul-token=<token> 56 Sets the Consul API token 57 58 -consul-transport-dial-keep-alive=<duration> 59 Sets the amount of time to use for keep-alives 60 61 -consul-transport-dial-timeout=<duration> 62 Sets the amount of time to wait to establish a connection 63 64 -consul-transport-disable-keep-alives 65 Disables keep-alives (this will impact performance) 66 67 -consul-transport-max-idle-conns-per-host=<int> 68 Sets the maximum number of idle connections to permit per host 69 70 -consul-transport-tls-handshake-timeout=<duration> 71 Sets the handshake timeout 72 73 -dedup 74 Enable de-duplication mode - reduces load on Consul when many instances of 75 Consul Template are rendering a common template 76 77 -dry 78 Print generated templates to stdout instead of rendering 79 80 -exec=<command> 81 Enable exec mode to run as a supervisor-like process - the given command 82 will receive all signals provided to the parent process and will receive a 83 signal when templates change 84 85 -exec-kill-signal=<signal> 86 Signal to send when gracefully killing the process 87 88 -exec-kill-timeout=<duration> 89 Amount of time to wait before force-killing the child 90 91 -exec-reload-signal=<signal> 92 Signal to send when a reload takes place 93 94 -exec-splay=<duration> 95 Amount of time to wait before sending signals 96 97 -kill-signal=<signal> 98 Signal to listen to gracefully terminate the process 99 100 -log-level=<level> 101 Set the logging level - values are "debug", "info", "warn", and "err" 102 103 -max-stale=<duration> 104 Set the maximum staleness and allow stale queries to Consul which will 105 distribute work among all servers instead of just the leader 106 107 -once 108 Do not run the process as a daemon 109 110 -pid-file=<path> 111 Path on disk to write the PID of the process 112 113 -reload-signal=<signal> 114 Signal to listen to reload configuration 115 116 -retry=<duration> 117 The amount of time to wait if Consul returns an error when communicating 118 with the API 119 120 -syslog 121 Send the output to syslog instead of standard error and standard out. The 122 syslog facility defaults to LOCAL0 and can be changed using a 123 configuration file 124 125 -syslog-facility=<facility> 126 Set the facility where syslog should log - if this attribute is supplied, 127 the -syslog flag must also be supplied 128 129 -template=<template> 130 Adds a new template to watch on disk in the format 'in:out(:command)' 131 132 -vault-addr=<address> 133 Sets the address of the Vault server 134 135 -vault-renew-token 136 Periodically renew the provided Vault API token - this defaults to "true" 137 and will renew the token at half of the lease duration 138 139 -vault-retry 140 Use retry logic when communication with Vault fails 141 142 -vault-retry-attempts=<int> 143 The number of attempts to use when retrying failed communications 144 145 -vault-retry-backoff=<duration> 146 The base amount to use for the backoff duration. This number will be 147 increased exponentially for each retry attempt. 148 149 -vault-ssl 150 Specifies is communications with Vault should be done via SSL 151 152 -vault-ssl-ca-cert=<string> 153 Sets the path to the CA certificate to use for TLS verification 154 155 -vault-ssl-ca-path=<string> 156 Sets the path to the CA to use for TLS verification 157 158 -vault-ssl-cert=<string> 159 Sets the path to the certificate to use for TLS verification 160 161 -vault-ssl-key=<string> 162 Sets the path to the key to use for TLS verification 163 164 -vault-ssl-server-name=<string> 165 Sets the name of the server to use when validating TLS. 166 167 -vault-ssl-verify 168 Enable SSL verification for communications with Vault. 169 170 -vault-token=<token> 171 Sets the Vault API token 172 173 -vault-transport-dial-keep-alive=<duration> 174 Sets the amount of time to use for keep-alives 175 176 -vault-transport-dial-timeout=<duration> 177 Sets the amount of time to wait to establish a connection 178 179 -vault-transport-disable-keep-alives 180 Disables keep-alives (this will impact performance) 181 182 -vault-transport-max-idle-conns-per-host=<int> 183 Sets the maximum number of idle connections to permit per host 184 185 -vault-transport-tls-handshake-timeout=<duration> 186 Sets the handshake timeout 187 188 -vault-unwrap-token 189 Unwrap the provided Vault API token (see Vault documentation for more 190 information on this feature) 191 192 -wait=<duration> 193 Sets the 'min(:max)' amount of time to wait before writing a template (and 194 triggering a command) 195 196 -v, -version 197 Print the version of this daemon
這里介紹下幾個常用參數的作用:
1 -consul-auth=<username[:password]> 設置基本的認證用戶名和密碼。 2 -consul-addr=<address> 設置Consul實例的地址。 3 -max-stale=<duration> 查詢過期的最大頻率,默認是1s。 4 -dedup 啟用重復數據刪除,當許多consul template實例渲染一個模板的時候可以降低consul的負載。 5 -consul-ssl 使用https連接Consul。 6 -consul-ssl-verify 通過SSL連接的時候檢查證書。 7 -consul-ssl-cert SSL客戶端證書發送給服務器。 8 -consul-ssl-key 客戶端認證時使用的SSL/TLS私鑰。 9 -consul-ssl-ca-cert 驗證服務器的CA證書列表。 10 -consul-token=<token> 設置Consul API的token。 11 -syslog 把標准輸出和標准錯誤重定向到syslog,syslog的默認級別是local0。 12 -syslog-facility=<facility> 設置syslog級別,默認是local0,必須和-syslog配合使用。 13 -template=<template> 增加一個需要監控的模板,格式是:'templatePath:outputPath(:command)',多個模板則可以設置多次。 14 -wait=<duration> 當呈現一個新的模板到系統和觸發一個命令的時候,等待的最大最小時間。如果最大值被忽略,默認是最小值的4倍。 15 -retry=<duration> 當在和consul api交互的返回值是error的時候,等待的時間,默認是5s。 16 -config=<path> 配置文件或者配置目錄的路徑。 17 -pid-file=<path> PID文件的路徑。 18 -log-level=<level> 設置日志級別,可以是"debug","info", "warn" (default), and "err"。 19 -dry Dump生成的模板到標准輸出,不會生成到磁盤。 20 -once 運行consul-template一次后退出,不以守護進程運行。
Consul-Template模版語法
Consul-Template模板文件的語法和Go Template的格式一樣,Confd也是遵循Go Template的。
這里主要說下API相關的函數:
- datacenters
在Consul目錄中查詢所有的數據中心。使用以下語法:
{{datacenters}}
- file
讀取並輸出磁盤上的本地文件,如果無法讀取產生一個錯誤。使用如下語法:
{{file "/path/to/local/file"}}
這個例子將輸出/path/to/local/file
文件內容到模板. 注意:這不會在嵌套模板中被處理。
- key
查詢Consul指定key的值,如果key的值不能轉換為字符串,將產生錯誤。使用如下語法:
{{key "service/redis/maxconns@east-aws"}}
上面的例子查詢了在east-aws數據中心的service/redis/maxconns的值。如果忽略數據中心參數,將會查詢本地數據中心的值:
{{key "service/redis/maxconns"}}
- keyOrDefault
查詢Consul中指定的key的值,如果key不存在,則返回默認值。使用方式如下:
{{keyOrDefault "service/redis/maxconns@east-aws" "5"}}
注意Consul Template使用了多個階段的運算。在第一階段的運算如果Consul沒有返回值,則會一直使用默認值。后續模板解析中如果值存在了則會讀取真實的值。Consul Templae不會因為keyOrDefault沒找到key而阻塞模板的的渲染。即使key存在如果Consul沒有按時返回這個數據,也會使用默認值來進行替代。
- ls
查看Consul的所有以指定前綴開頭的key-value對。如果有值無法轉換成字符串則會產生一個錯誤:
{{range ls "service/redis@east-aws"}}
{{.Key}} {{.Value}}{{end}}
如果Consul實例在east-aws數據中心存在這個結構service/redis,渲染后的模板應該類似這樣:
minconns 2
maxconns 12
如果你忽略數據中心屬性,則會返回本地數據中心的查詢結果。
- node
查詢目錄中的一個節點信息。
{{node "node1"}}
如果未指定任何參數,則當前Agent所在節點將會被返回:
{{node}}
你可以指定一個可選的參數來指定數據中心:
{{node "node1" "@east-aws"}}
如果指定的節點沒有找到則會返回nil,如果節點存在就會列出節點的信息和節點提供的服務。
{{with node}}{{.Node.Node}} ({{.Node.Address}}){{range .Services}}
{{.Service}} {{.Port}} ({{.Tags | join ","}}){{end}}
{{end}}
- nodes
查詢Consul目錄中的全部節點,使用如下語法:
{{nodes}}
這個例子會查詢Consul的默認數據中心。你可以使用可選參數指定一個可選參數來指定數據中心:
{{nodes "@east-aws"}}
這個例子會查詢east-aws數據中心的所有節點。
- secret
查詢Vault中指定路徑的密匙,如果指定的路徑不存在或者Vault的Token沒有足夠權限去讀取指定的路徑,將會產生一個錯誤。如果路徑存在但是key不存在則返回<no value>
。
{{with secret "secret/passwords"}}{{.Data.password}}{{end}}
- service
查詢Consul中匹配表達式的服務,語法如下:
{{service "release.web@east-aws"}}
上面的例子查詢Consul中,在east-aws數據中心存在的健康的web服務。tag和數據中心參數是可選的,從當前數據中心查詢所有節點的web服務而不管tag。查詢語法如下:
{{service "web"}}
這個函數返回[]*HealthService
結構.可按照如下方式應用到模板:
{{range service "web@data center"}}
server {{.Name}} {{.Address}}:{{.Port}}{{end}}
產生類似如下輸出:
server nyc_web_01 1.2.3.4:8080
server nyc_web_02 10.20.30.40:8080
默認值會返回健康的服務。如果你想獲取所有服務,可以增加any選項。如下:
{{service "web" "any"}}
這樣就會返回注冊過的所有服務,而不論它的狀態如何。
如果你想過濾指定的一個或者多個健康狀態,你可以通過逗號隔開多個健康狀態:
{{service "web" "passing, warning"}}
這樣將會返回被它們的節點和服務級別的檢查定義標記為"passing"或者"warning"的服務。請注意逗號是OR而不是AND的意思。指定了超過一個狀態過濾,並包含any將會返回一個錯誤。因為any是比所有狀態更高級的過濾。
后面這2種方式有些架構上的不同:
{{service "web"}}
{{service "web" "passing"}}
前者會返回Consul認為healthy和passing的所有服務。后者將返回所有已經在Consul注冊的服務,然后會執行一個客戶端的過濾。通常如果你想獲取健康的服務,你應該不要使用passing參數。直接忽略第三個參數即可。然而第三個參數在你想查詢passing或者warning的服務會比較有用,如下:
{{service "web" "passing, warning"}}
服務的狀態也是可見的,如果你想自己做一些額外的過濾。語法如下:
{{range service "web" "any"}}
{{if eq .Status "critical"}}
// Critical state!{{end}}
{{if eq .Status "passing"}}
// Ok{{end}}
執行命令時,在Consul將服務設置為維護模式只需要在你的命令上包上Consul的maint調用:
#!/bin/sh set -e consul maint -enable -service web -reason "Consul Template updated" service nginx reload consul maint -disable -service web
另外如果你沒有安裝Consul agent,你可以直接調用API請求:
#!/bin/sh set -e curl -X PUT "http://$CONSUL_HTTP_ADDR/v1/agent/service/maintenance/web?enable=true&reason=Consul+Template+Updated" service nginx reload curl -X PUT "http://$CONSUL_HTTP_ADDR/v1/agent/service/maintenance/web?enable=false"
- services
查詢Consul目錄中的所有服務,使用如下語法:
{{services}}
這個例子將查詢Consul的默認數據中心,你可以指定一個可選參數來指定數據中心:
{{services "@east-aws"}
請注意: services函數與service是不同的,service接受更多參數並且查詢監控的服務列表。這個查詢Consul目錄並返回一個服務的tag的Map。如下:
{{range services}}
{{.Name}}
{{range .Tags}}
{{.}}{{end}}
{{end}}
- tree
查詢所有指定前綴的key-value值對,如果其中的值有無法轉換為字符串的則引發錯誤:
{{range tree "service/redis@east-aws"}}
{{.Key}} {{.Value}}{{end}}
如果Consul實例在east-aws數據中心有一個service/redis結構,模板的渲染結果類似下面:
minconns 2
maxconns 12
nested/config/value "value"
和ls不同tree返回前綴下的所有key,和Unix的tree命令比較像。如果忽略數據中心參數,則會使用本地數據中心。
更多輔助函數,比如 scratch、byKey、byTag、contains、explode、in、loop、trimSpace、join、parseBool、parseFloat、parseInt、parseJSON、parseUint、regexMatch等可參考:https://github.com/hashicorp/consul-template#templating-language
Consul-Template使用實例
在進行以下測試前,你首先得有一個Consul集群。如果你還沒有,可參考「Consul集群部署」 一文搭建一個。
命令行方式
- 輸出已注冊服務的名稱和Tags。
創建一個服務文件
$ vim /opt/consul/conf/hi-linux.json {"service": {"name": "hi-linux", "tags": ["web"], "port": 8080, "check": {"http": "http://192.168.2.210:8080", "interval": "10s"}}}
通過consul reload
進行熱注冊
$ consul reload --http-addr=192.168.2.210:8500
Configuration reload triggered
驗證服務是否注冊成功
$ curl http://192.168.2.210:8500/v1/catalog/service/hi-linux [{"ID":"7d3b4fa3-b284-b761-f973-d856cd41ab7a","Node":"consul-server01","Address":"192.168.2.210","TaggedAddresses":{"lan":"192.168.2.210","wan":"192.168.2.210"},"NodeMeta":{},"ServiceID":"hi-linux","ServiceName":"hi-linux","ServiceTags":["web"],"ServiceAddress":"","ServicePort":8080,"ServiceEnableTagOverride":false,"CreateIndex":4985,"ModifyIndex":4985}]
創建模板文件
$ vim tmpltest.ctmpl
{{range services}}
{{.Name}}
{{range .Tags}}
{{.}}{{end}}
{{end}}
調用模板文件生成查詢結果
$ consul-template -consul-addr 192.168.2.210:8500 -template "tmpltest.ctmpl:result" -once
命令說明:
-consul-addr:指定Consul的API接口 ,默認是8500端口。
-template:模板參數,第一個參數是模板文件位置,第二個參數是結果輸出位置。
-once:只運行一次就退出。
查看模板渲染的結果
$ cat result consul hi-linux web
輸出結果說明:consul是系統自帶的服務,hi-linux是剛才注冊的服務,其Tags為web。
- 根據已注冊的服務動態生成Nginx配置文件
新建Nginx配置模板文件
$ vim nginx.conf.ctmpl {{range services}} {{$name := .Name}} {{$service := service .Name}} upstream {{$name}} { zone upstream-{{$name}} 64k; {{range $service}}server {{.Address}}:{{.Port}} max_fails=3 fail_timeout=60 weight=1; {{else}}server 127.0.0.1:65535; # force a 502{{end}} } {{end}} server { listen 80 default_server; location / { root /usr/share/nginx/html/; index index.html; } location /stub_status { stub_status; } {{range services}} {{$name := .Name}} location /{{$name}} { proxy_pass http://{{$name}}; } {{end}} }
調用模板文件生成Nginx配置文件
$ consul-template -consul-addr 192.168.2.210:8500 -template="nginx.conf.ctmpl:default.conf" -once # 渲染后的Nginx配置文件 $ cat default.conf upstream consul { zone upstream-consul 64k; server 192.168.2.210:8300 max_fails=3 fail_timeout=60 weight=1; server 192.168.2.211:8300 max_fails=3 fail_timeout=60 weight=1; server 192.168.2.212:8300 max_fails=3 fail_timeout=60 weight=1; } upstream hi-linux { zone upstream-hi-linux 64k; server 192.168.2.210:8080 max_fails=3 fail_timeout=60 weight=1; } upstream web { zone upstream-web 64k; server 192.168.2.210:8080 max_fails=3 fail_timeout=60 weight=1; } server { listen 80 default_server; location / { root /usr/share/nginx/html/; index index.html; } location /stub_status { stub_status; } location /consul { proxy_pass http://consul; } location /hi-linux { proxy_pass http://hi-linux; } }
如果想生成Nginx配置文件后自動加載配置,可以這樣:
$ consul-template -consul-addr 192.168.2.210:8500 -template="nginx.conf.ctmpl:/usr/local/nginx/conf/conf.d/default.conf:service nginx reload" -once
- 運行consul-temple作為一個服務
上面兩個例子都是consul-template運行一次后就退出了,如果想運行為一個服務可以這樣:
$ consul-template \ -consul-addr=192.168.2.210:8500 \ -template "tmpltest.ctmpl:test.out"
- 查詢Consul實例同時渲染多個模板,然后重啟相關服務。如果API故障則每30s嘗試檢測一次值,consul-template運行一次后退出。
$ consul-template \ -consul-addr=192.168.2.210:8500 \ -retry 30s \ -once \ -template "nginx.ctmpl:/etc/nginx/nginx.conf:service nginx restart" \ -template "redis.ctmpl:/etc/redis/redis.conf:service redis restart" \ -template "haproxy.ctmpl:/etc/haproxy/haproxy.conf:service haproxy restart"
- 查詢一個實例,Dump模板到標准輸出。主要用作測試模板輸出。
$ consul-template \ -consul-addr=192.168.2.210:8500 \ -template "tmpltest.ctmpl:result" \ -once \ -dry
配置文件方式
以上參數除了在命令行使用也可以直接配置在文件中,下面看看Consul-Template的配置文件,簡稱HCL(HashiCorp Configuration Language),它是和JSON兼容的。
下面先看看官方給的配置文件格式:
consul { auth { enabled = true username = "test" password = "test" } address = "192.168.2.210:8500" token = "abcd1234" retry { enabled = true attempts = 5 backoff = "250ms" } ssl { enabled = true verify = false cert = "/path/to/client/cert" key = "/path/to/client/key" ca_cert = "/path/to/ca" ca_path = "path/to/certs/" server_name = "my-server.com" } } reload_signal = "SIGHUP" dump_signal = "SIGQUIT" kill_signal = "SIGINT" max_stale = "10m" log_level = "warn" pid_file = "/path/to/pid" wait { min = "5s" max = "10s" } vault { address = "https://vault.service.consul:8200" token = "abcd1234" unwrap_token = true renew_token = true retry { # ... } ssl { # ... } } syslog { enabled = true facility = "LOCAL5" } deduplicate { enabled = true prefix = "consul-template/dedup/" } exec { command = "/usr/bin/app" splay = "5s" env { pristine = false custom = ["PATH=$PATH:/etc/myapp/bin"] whitelist = ["CONSUL_*"] blacklist = ["VAULT_*"] } reload_signal = "" kill_signal = "SIGINT" kill_timeout = "2s" } template { source = "/path/on/disk/to/template.ctmpl" destination = "/path/on/disk/where/template/will/render.txt" contents = "{{ keyOrDefault \"service/redis/maxconns@east-aws\" \"5\" }}" command = "restart service foo" command_timeout = "60s" perms = 0600 backup = true left_delimiter = "{{" right_delimiter = "}}" wait { min = "2s" max = "10s" } }
更多詳細的參數可以參考這里: https://github.com/hashicorp/consul-template#configuration-file-format
注意: 上面的選項不都是必選的,可根據實際情況調整。為了更加安全,token也可以從環境變量里讀取,使用CONSUL_TOKEN
和VAULT_TOKEN
。強烈建議你不要把token放到未加密的文本配置文件中。
接下來我們看一個簡單的實例,生成Nginx配置文件並重新加載:
$ vim nginx.hcl consul { address = "192.168.2.210:8500" } template { source = "nginx.conf.ctmpl" destination = "/usr/local/nginx/conf/conf.d/default.conf" command = "service nginx reload" }
注:nginx.conf.ctmpl模板文件內容還是和前面的一樣。
執行以下命令就可渲染文件了:
$ consul-template -config "nginx.hcl"
更多官方例子可參考:https://github.com/hashicorp/consul-template/tree/master/examples