Met*_*tro 2 amazon-web-services terraform terraform-provider-aws terraform0.12+
我有许多 Terraform 数据源和一个这样创建的本地块
data "aws_subnets" "subs" {
for_each = toset(["a", "b", "c"])
filter {
name = "vpc-id"
values = [data.aws_vpc.vpc.id]
}
filter {
name = "availability-zone"
values = ["${data.aws_region.region.name}${each.key}"]
}
}
data "aws_vpc" "vpc" {
default = false
}
data "aws_region" "region" {}
locals {
ids = [for az in data.aws_subnets.subs : az.ids[1]]
}
Run Code Online (Sandbox Code Playgroud)
和一个输出块
output "main" {
value = local.ids
}
Run Code Online (Sandbox Code Playgroud)
但是当我运行 terraform apply 时出现错误
The given key does not identify an element in this collection value: the given index is greater than or equal to the length of the collection
当我从 locals 块中取出索引值时[1],我可以看到输出为
+ main = [
+ [
+ "subnet-1234567f3f5d95987",
+ "subnet-123456797f61f831e",
+ "subnet-123456791ec481316",
],
+ [
+ "subnet-12345674da33e8064",
+ "subnet-12345676030bc7040",
],
+ [],
]
Run Code Online (Sandbox Code Playgroud)
如何从此列表中提取特定子网 ID?
这里你必须考虑两件事:
for_each数据源,因此这意味着返回结果将具有键值对为了达到你想要的效果,需要修改如下代码:
data "aws_subnets" "subs" {
for_each = toset(["a", "b", "c"])
filter {
name = "vpc-id"
values = [data.aws_vpc.vpc.id]
}
filter {
name = "availability-zone"
values = ["${data.aws_region.region.name}${each.key}"]
}
}
data "aws_vpc" "vpc" {
default = false
}
data "aws_region" "region" {}
locals {
ids = values(data.aws_subnets.subs)[*].ids
}
Run Code Online (Sandbox Code Playgroud)
这里,内置的values[1] 函数用于获取所有键的所有值。返回结果也是一个列表,因此这将是一个列表的列表。
[1] https://developer.hashicorp.com/terraform/language/functions/values
| 归档时间: |
|
| 查看次数: |
841 次 |
| 最近记录: |