【发布时间】:2021-07-13 16:06:23
【问题描述】:
我对 terraform 还不够新,我认为我误解了 count 和 count.index 用法。
我正在使用 count 参数创建一些 EC2 实例,它工作正常
resource "aws_instance" "server" {
ami = data.aws_ami.app_ami.id
instance_type = "t2.micro"
key_name = "DeirdreKey"
subnet_id = aws_subnet.my_subnet_a.id
count = 2
tags = {
Name = "server.${count.index}"
}
我想将一个安全组与两个实例相关联,所以我创建了以下
resource "aws_network_interface_sg_attachment" "sg_attachment" {
security_group_id = aws_security_group.allow_internet.id
network_interface_id = aws_instance.server.primary_network_interface_id
}
但是我遇到了这个错误
Error: Missing resource instance key
on lb.tf line 57, in resource "aws_network_interface_sg_attachment" "sg_attachment":
57: network_interface_id = aws_instance.server.primary_network_interface_id
Because aws_instance.server has "count" set, its attributes must be
accessed on specific instances.
For example, to correlate with indices of a referring resource, use:
aws_instance.server[count.index]
我了解错误在抱怨什么。这是因为我所指的本地资源名称不是唯一的,因为我创建了 2 个称为“服务器”的 aws 实例。我不知道如何解决它。我尝试了以下
resource "aws_network_interface_sg_attachment" "sg_attachment" {
security_group_id = aws_security_group.allow_internet.id
network_interface_id = aws_instance.server[count.index].primary_network_interface_id
然后我得到以下错误
Error: Reference to "count" in non-counted context
on lb.tf line 53, in resource "aws_network_interface_sg_attachment" "sg_attachment":
53: network_interface_idaws_instance.server[count.index].primary_network_interface_id
The "count" object can only be used in "module", "resource", and "data"
blocks, and only when the "count" argument is set.
这是否意味着我必须将 count.index 引入本地资源名称?试了好几种方法都没有效果
resource "aws_instance" "server${count.index}" {
【问题讨论】: