【发布时间】:2018-10-03 15:07:48
【问题描述】:
我正在使用 Terraform 设置多个在 DigitalOcean 上运行 Consul 的液滴。也许我遗漏了一些基本的东西,但为它们提供正确的配置似乎非常困难。
resource "digitalocean_droplet" "prime" {
count = 3
image = "${data.digitalocean_image.prime.image}"
name = "${format("%s-%02d-%s", "prime", count.index + 1, var.region)}"
private_networking = true
# ...
}
每台机器都有两个网络接口——公共的和私有的。使用此设置,似乎有必要提供指向每个 droplet 的私有 IP 地址的 bind_addr - 否则 consul 退出时会出现错误,指出有多个私有 (?!) 地址。
最直接的解决方案是为每台机器配置一个在每种情况下几乎相同的配置文件,但 bind_addr 字段的值不同,如下所示:
{
"server": true,
"data_dir": "/var/consul/data",
"ui": true,
"bind_addr": "${ private_ipv4_address }"
}
这不是模板的用途吗?我不知道如何以这种方式使用它们。似乎模板的变量只能在定义模板时提供一次:
data "template_file" "consul-config" {
template = "${file("templates/consul-config.json.tpl")}"
vars {
private_ipv4_address = "10.0.0.1" # At this point the real address is not known
}
}
resource "digitalocean_droplet" "prime" {
...
provisioner "file" {
content = "${data.template_file.consul-config.rendered}"
destination = "/etc/consul.d/server.json"
# At this point the address is known: ${ self.private_ipv4_address },
# but is it possible to pass it to the template?
}
}
我尝试将数据块嵌套在资源块中,但随后出现如下错误:
Error: resource 'digitalocean_droplet.prime' provisioner file (#7): unknown resource 'data.template_file.consul-config' referenced in variable data.template_file.consul-config.rendered
我目前使用的解决方法是将配置拆分为两部分(服务器和自定义)并将自定义的内容内联到文件配置器中:
resource "digitalocean_droplet" "prime" {
# ...
provisioner "file" {
content = "${data.template_file.consul-config.rendered}"
destination = "/etc/consul.d/server.json"
}
# This is a custom configuration for each particular droplet
provisioner "file" {
content = "{ \"bind_addr\": \"${ self.ipv4_address_private }\", \"bootstrap\": ${ count.index == 0 } }"
destination = "/etc/consul.d/custom.json"
}
}
它可以工作,但由于以下几个原因阻碍了可读性:
所有引号都必须转义
所有内容都必须在单行上 (?)
文本编辑器没有语法高亮或类似帮助
另外,我考虑使用外部程序(如envsubst)来渲染模板或使用built in format function 和file function,但每个都看起来很麻烦。
有没有直接的方法来实现我想要的?
【问题讨论】:
标签: digital-ocean terraform terraform-template-file