【问题标题】:Terraform issue attaching a security group to my aws instances将安全组附加到我的 aws 实例的 Terraform 问题
【发布时间】: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}" {

【问题讨论】:

    标签: count terraform


    【解决方案1】:

    您需要对资源的计数语句才能使用count.index。计数语句可能会失控,因此如果您有多个在逻辑上需要相同计数的资源,请使用变量或局部值:

    local {
      replications = 2
    }
    
    resource "aws_instance" "server" {
      count = local.replications
      ami = data.aws_ami.app_ami.id
      instance_type = "t2.micro"
      key_name = "DeirdreKey"
      subnet_id = aws_subnet.my_subnet_a.id
      tags = {
        Name = "server.${count.index}"
      }
    }
    
    resource "aws_network_interface_sg_attachment" "sg_attachment" {
      count                = local.replications
      security_group_id    = aws_security_group.allow_internet.id
      network_interface_id = aws_instance.server[count.index].primary_network_interface_id
    }
    

    这会为每台服务器创建一个安全组附件,并为您提供可以引用为 aws_instance.server[0]aws_instance.server[1] 的服务器列表,以及可以以相同方式引用的附件列表。

    【讨论】:

    • 谢谢!现在更有意义了!
    猜你喜欢
    • 1970-01-01
    • 2020-08-25
    • 2020-12-06
    • 2021-11-30
    • 2017-03-17
    • 2021-05-08
    • 1970-01-01
    • 2018-10-24
    • 1970-01-01
    相关资源
    最近更新 更多