遇到了这样的问题。我想不出如何创建这样的temlate_file:
[master] ser1 ansible_host=10.0.0.1 ser2 ansible_host=10.0.0.2
以便从更改中生成名称和地址。我在date.tf中使用标准结构:
data "template_file" "inventory" {
count = length(var.domains)
template = file("inventory.tpl")
vars = {
master_ip = join("\n", hcloud_server.rebrain_quest.*.ipv4_address)
key_path = var.privat_key
}
}但在这里我只能生成我的地址。
[master] 10.0.0.1 10.0.0.2
你可能需要一些这样的方法,但我没有任何东西出来:
master_ip = join(";", [hcloud_server.rebrain_quest.*.name, ansible_host=, hcloud_server.rebrain_quest.*.ipv4_address])我有terraform版本v0.12.24
发布于 2020-05-05 04:33:38
因为您使用的是Terraform0.12,所以应该使用the templatefile function而不是template_file数据源。因为它是内置在语言中的,而不是由提供程序提供的,所以它不受数据源的限制,比如强制所有vars值为字符串。
locals {
ansible_inventory = templatefile("${path.module}/inventory.tpl", {
hosts = hcloud_server.rebrain_quest
})
}然后在模板文件中:
[master]
%{ for h in hosts ~}
${h.name} ansible_host=${h.ipv4_address}
%{ endfor ~}上面的模板是the documentation about Terraform's template directive syntax中给出的示例的变体。
您最初的示例包含count = var.domains,但是资源配置的其余部分没有提到count.index,所以我认为实际上并不需要这样做。但是,如果您确实希望根据var.domains中的数量创建模板的多个副本,则可以使用以下变体:
locals {
ansible_inventory = [
for i in range(var.domains) :
templatefile("${path.module}/inventory.tpl", {
hosts = hcloud_server.rebrain_quest
index = i
})
]
}The range function在这里创建了一个从0到var.domains - 1的整数列表,所以我们可以在for中使用它来多次重复模板渲染。我将index = i添加到template variables对象中,这样您就可以在原则上在模板中使用${i},以获得与资源块中的count.index类似的效果。
发布于 2020-05-04 22:55:01
Terraform:
data "template_file" "inventory" {
count = length(var.domains)
template = file("inventory.tpl")
vars = {
hosts = hcloud_server.rebrain_quest
lines = [
for h in hcloud_server.rebrain_quest:
]
}
}模板:
[master]
%{ for h in hosts ~}
${h.name} ansible_host=${h.ipv4_address}
%{ endfor ~}但可以考虑使用terraform-ansible (有很多),使用hcloud dynamic inventory plugin或通过hcloud_server_info使用ad-hoc hcloud发现
发布于 2020-05-05 20:43:18
感谢大家的回答,我用一个复杂的表达式解决了这个问题:
master_ip = "${join("\n", [for instance in hcloud_server.rebrain_quest : join("", [instance.name, " ansible_host=", instance.ipv4_address])] )}"https://stackoverflow.com/questions/61578490
复制相似问题