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

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