如何在 Terraform 中迭代 'count' 资源?
How do I iterate over a 'count' resource in Terraform?
在这个例子中,我试图创建 3 个 EC2 实例,每个实例都分配了一个弹性 IP。我想通过下面的话来实现这一点。
resource "aws_instance" "web_servers" {
ami = "ami-09e67e426f25ce0d7"
instance_type = "t3.micro"
...
count = 3
}
并且,连同其他网络实例,
resource "aws_eip" "elastic_ip" {
for_each = aws_instance.web_servers
instance = each.key
vpc = true
}
但是,这是在说以下内容:
The given "for_each" argument value is unsuitable: the "for_each" argument must be a map, or set of strings, and you have provided a value of type tuple.
我已经尝试将 for_each
包装在 toset()
中,这也表示存在未知数量的问题 - 虽然我知道有 3 个。我在 count
和 for_each
关键字周围遗漏了什么吗?
如果你真的要用for_each
,而不是再算一次,应该是:
resource "aws_eip" "elastic_ip" {
for_each = {for idx, val in aws_instance.web_servers: idx => val}
instance = each.value.id
vpc = true
}
但由于您首先使用的是 count
,因此最好也将 count
用于 aws_eip
:
resource "aws_eip" "elastic_ip" {
count = length(aws_instance.web_servers)
instance = aws_instance.web_servers[count.index].id
vpc = true
}
在 AWS 中您的实例字段 = EC2 ID = ARN?
如果是这样,您也许可以访问 aws_instance
资源块中的 arn
属性。
您可以尝试 toset(aws_instance.web_servers.arn)
并保持 instance = each.key
。我通常只使用 each.value
但在处理集合时它们应该相同。
在这个例子中,我试图创建 3 个 EC2 实例,每个实例都分配了一个弹性 IP。我想通过下面的话来实现这一点。
resource "aws_instance" "web_servers" {
ami = "ami-09e67e426f25ce0d7"
instance_type = "t3.micro"
...
count = 3
}
并且,连同其他网络实例,
resource "aws_eip" "elastic_ip" {
for_each = aws_instance.web_servers
instance = each.key
vpc = true
}
但是,这是在说以下内容:
The given "for_each" argument value is unsuitable: the "for_each" argument must be a map, or set of strings, and you have provided a value of type tuple.
我已经尝试将 for_each
包装在 toset()
中,这也表示存在未知数量的问题 - 虽然我知道有 3 个。我在 count
和 for_each
关键字周围遗漏了什么吗?
如果你真的要用for_each
,而不是再算一次,应该是:
resource "aws_eip" "elastic_ip" {
for_each = {for idx, val in aws_instance.web_servers: idx => val}
instance = each.value.id
vpc = true
}
但由于您首先使用的是 count
,因此最好也将 count
用于 aws_eip
:
resource "aws_eip" "elastic_ip" {
count = length(aws_instance.web_servers)
instance = aws_instance.web_servers[count.index].id
vpc = true
}
在 AWS 中您的实例字段 = EC2 ID = ARN?
如果是这样,您也许可以访问 aws_instance
资源块中的 arn
属性。
您可以尝试 toset(aws_instance.web_servers.arn)
并保持 instance = each.key
。我通常只使用 each.value
但在处理集合时它们应该相同。