confd模板配置說明(變量、函數和語法)

參考鏈接:http://www.ruanyifeng.com/blog/2019/09/curl-reference.html

1、模板內內嵌的語法支持,全部需要加{{}}來標記
2、在模板文件內, . 代表了當前變量,即在非循環體內,.就代表了傳入的那個變量
3、模板內的變量定義方法: {{$variable := value}},例如:

{{$username := "jhon"}}

假設我們定義了一個結構體:

type Article struct {
    ArticleId int
    ArticleContent string
}

那麼我們在模板內可以通過.ArticleContent和.ArticleId的方式來獲取並把變量的內容渲染到模板內。

{{.ArticleContent}}{{.ArticleId}}

4、with語句創建一個封閉的作用域,在其範圍內,可以使用.action,而與外面的.無關,只與with的參數有關:

{{ with arg }}
    此時的點 . 就是arg
{{ end }}

5、循環依靠range語句

{{range gets "/services/zookeeper/*"}}
{{$data := json .Value}}
  id: {{$data.Id}}
  ip: {{$data.IP}}
{{end}}

6、如果取回的值是json格式的,可以創建一個map
例如: etcdctl set /myapp/upstream/app1 ‘{“IP”: “99.99.99.99”,“NAME”: “jhon”}’

{{with get "/myapp/upstream/app1"}}
  key: {{base .Key}}
  {{$data := json .Value}}
  Ipaddress: {{$data.IP}} Username: {{$data.NAME}}
{{end}}

7、confd一些常用的函數
get 返回匹配的“鍵-值”對
gets 返回所有匹配的“鍵-值”對

getv 返回匹配“鍵”的“值”
getvs 返回所有匹配“鍵”的“值”

ls 返回指定路徑下的所有子鍵
lsdir 返回指定路徑下所有具有子目錄的子鍵
dir 返回指定“鍵”的父目錄
exist 檢查指定的“鍵”是否存在
base 返回路徑的最後一個元素

另有一些go函數的別名,具體用法看文檔
join
split
replace
toUpper
toLower
getenv
datatime

一個nginx 模板的例子:

{{$domains := ls "/XXX-1.1.1.1"}}   // 獲取指定/XXX-1.1.1.1鍵下所有子健
{{range $domain := $domains}}       // 循環取出list中的子健
    {{if ne $domain "mesproxy"}}    // 判斷子健不等於"mesproxy"
        {{$epg_key := printf "/XXX-1.1.1.1/%s" $domain}}     // 定義變量等於/XXX-1.1.1.1/鍵
        {{if getv $epg_key}}        // 判斷epg_key中子健存在
            server {{ getv $epg_key "2.2.2.2"}}:8080 max_fails=5;    // {{}}存放$epg_key中的子健,"2.2.2.2"是默認值
        {{else}}
        {{end}}
    {{end}}
{{end}}

參考文檔:
https://github.com/kelseyhightower/confd/blob/master/docs/templates.md — >官方文檔
https://seanmcgary.com/posts/automatically-scale-haproxy-with-confd-and-etcd/
https://www.jianshu.com/p/05671bab2357
https://www.cnblogs.com/iamdoufu/p/4533063.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章