gpt4 book ai didi

terraform - 如何在 Terraform 资源循环中使用非唯一键创建唯一资源

转载 作者:行者123 更新时间:2023-12-04 08:05:01 30 4
gpt4 key购买 nike

我想使用通用模块为域创建每种类型的 DNS 记录,因此能够用类似的方式调用它:

module "example_com_dns" {
source = "[PATH_TO_MODULES]/modules/dns"

domain = "example.com"

a_records = {
"@" = [SOME IP]
"www" = [SOME IP]
"home" = [SOME IP]
}

txt_records = {
"@" = "txt-foobar1"
"@" = "txt-foobar2"
"mail._domainkey.self" = "foobar"
}

mx_entries = {
"10" = "mail.someprovider.com"
"20" = "mail2.someprovider.com"
}

cname_records {
"cname-foo" = "cname-bar
}
}

我有一些东西可以很好地用于 A、CNAME 和 MX 记录,但是 TXT 有一个我需要解决的边缘情况。我的模块为每种类型的记录提供了资源 block ,这些资源 block 通过循环运行。我只粘贴 TXT 文件,但它们都是一样的:

resource "digitalocean_record" "this_txt_record" {
for_each = var.txt_records

domain = var.domain
type = "TXT"
name = each.key
value = each.value
}

一切正常,除了因为有 2 条记录以“@”作为键,所以只创建了最后一条记录(在我上面的示例中,这是“txt-foobar2”):


...

# module.example_com.digitalocean_record.this_txt_record["@"] will be created
+ resource "digitalocean_record" "this_txt_record" {
+ domain = "example.com"
+ fqdn = (known after apply)
+ id = (known after apply)
+ name = "@"
+ ttl = (known after apply)
+ type = "TXT"
+ value = "txt-foobar2"
}

我希望它同时创建“txt-foobar1”和“txt-foobar2”,即使在 map 中给定了非唯一键也是如此。

也许这是错误的方式,我只需要找出一个聪明的循环来代替解析这个结构?:

  txt_records = [
{ "@" = "foo" },
{ "@" = "bar"},
{ "mail._domainkey.self" = "foobar"}
]

如果是这样,我目前也失败了:)

最佳答案

资源不能通过 for_each 列表来创建,因为必须有一个唯一的键,它将成为 terraform 资源名称的一部分。列表索引不是可靠的键,因为如果您对列表中的项目重新排序,您的 TF 计划将一团糟。

另一方面,根据定义, map 确实具有唯一键。

不过您可以从列表中生成 map !我发现了这个小技巧 here .请注意,您还需要手动计算唯一的映射键(${txt_record[0]}=${txt_record[1]} 在下面的示例中)。

已更新的资源:

module "example_com_dns" {
...

txt_records = [
["@", "txt-foobar1"],
["@", "txt-foobar2"],
["mail._domainkey.self", "foobar"],
]
}
resource "digitalocean_record" "this_txt_record" {
for_each = {for txt_record in var.txt_records: "${txt_record[0]}=${txt_record[1]}" => txt_record}

domain = var.domain
type = "TXT"
name = each.value[0]
value = each.value[1]
}

或者如果您愿意,可以稍微详细一点:

module "example_com_dns" {
...

txt_records = [
{name: "@", value: "txt-foobar1"},
{name: "@", value: "txt-foobar2"},
{name: "mail._domainkey.self", value: "foobar"},
]
}
resource "digitalocean_record" "this_txt_record" {
for_each = {for txt_record in var.txt_records: "${txt_record.name}=${txt_record.value}" => txt_record}

domain = var.domain
type = "TXT"
name = each.value.name
value = each.value.value
}

关于terraform - 如何在 Terraform 资源循环中使用非唯一键创建唯一资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66256261/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com