consul-template

介绍利用consul-template来生成 zone_file,以达到通过远程调用HTTP API 来管理consul, 进而利用consul-template来生成zone文件.

通过这里下载 & 安装最新版本的consul-template:

wget https://releases.hashicorp.com/consul-template/0.20.0/consul-template_0.20.0_linux_amd64.zip
unzip consul-template_0.20.0_linux_amd64.zip
mv consul-template /usr/local/bin/

配置文件:

cat > nginx.hcl << 'EOF'
consul {
address = "192.168.2.210:8500"
}
token = "xxxxxxxxxx"
template {
source = "nginx.conf.ctmpl"
destination = "/usr/local/nginx/conf/conf.d/default.conf"
command = "service nginx reload"
}
EOF
# 启动
consul-template -config "nginx.hcl"

# 开启渲染
consul-template -template "in.tpl:out.txt" [-once]
# 在consul中更新数据
consul kv put foo bar
 
# 多行渲染
consul-template \
    -template "/tmp/nginx.ctmpl:/var/nginx/nginx.conf:nginx -s reload" \
    -template "/tmp/redis.ctmpl:/var/redis/redis.conf:service redis restart" \
    -template "/tmp/haproxy.ctmpl:/var/haproxy/haproxy.conf"

3.1 实例1(zone file)

模板:

$ORIGIN {{ key "dns/domain" }}
$TTL 360

@ IN SOA ns1.{{ key "dns/domain" }} root.{{ key "dns/domain" }} (
        {{ key "dns/serial" }} ; Serial
        3600       ; Refresh
        900        ; Retry
        3600000    ; Expire
        60         ; Minimum
        )

;; RRs
        IN      NS      ns1.{{ key "dns/domain" }}
        IN      NS      ns2.{{ key "dns/domain" }}
ns1     IN      A       10.50.104.11
ns2     IN      A       10.50.104.12
{{range ls "dns/records" }}
{{ .Key }}	IN	A	{{ .Value }}{{ end }}

3.2 实例2 (nginx)

模板:

{{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}}

输出:

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;
}

  • linux/consul/consul_template.txt
  • 最后更改: 2019/04/18 16:46
  • 由 mrco