将AWS安全组附加到多个EC2实例

时间:2020-05-10 05:13:41

标签: amazon-ec2 terraform terraform-provider-aws aws-security-group terraform0.12+

我正在拆分多个Amazon EC2实例,需要附加一个安全组。我能够针对一个EC2实例实现此目标,但正在寻找针对多个EC2的解决方案。我正在使用TerraForm 0.12。请让我知道如何使用数据资源:-数据“ aws_instances”(s)。

这是我要转换为多个EC2的单个EC2的代码:

    resource "aws_instance" "ec2_instance" {
      count                = "${var.ec2_instance_count}"
      ami                  = "${data.aws_ami.app_qrm_ami.id}"
    ...
    }
    data "aws_instances" "ec2_instances" {
  count      = "${var.ec2_instance_count}"
  filter {
    name = "instance-id"
    values = ["${aws_instance.ec2_instance.*.id[count.index]}"]
  }
    }
    resource "aws_network_interface_sg_attachment" "sg_attachment" {
      security_group_id    = "${data.aws_security_group.security_group.id}"
      network_interface_id = "${data.aws_instance.ec2_instance[count.index].network_interface_id}" //facing issues here.
    }

我想使用数据“ aws_instances” #notice(s)实现此目的。预先感谢。

2 个答案:

答案 0 :(得分:2)

要删除ec2 AMI的硬编码,可以使用以下数据提供程序:-

  data "aws_ami" "amazon_linux" {
  count       = "${var.ec2_instance_count}"
  most_recent = true
  owners      = ["amazon"]

  filter {
    name = "name"
    values = [
      "amzn-ami-hvm-*-x86_64-gp2",
    ]
  }

  filter {
    name = "owner-alias"
    values = [
      "amazon",
    ]
  }
}

用于呈现ami id:-

resource "aws_instance" "ec2_instance" {
  count             = "${var.ec2_instance_count}"
  ami               = "${data.aws_ami.amazon_linux[count.index].id}"
  network_interface = 

要获取network_interface_id:-

resource "aws_network_interface" "ec2_nic" {
  count           = "${var.ec2_instance_count}"
  subnet_id       = "${aws_subnet.public_a.id}"
  private_ips     = ["10.0.0.50"]
  security_groups = ["${aws_security_group.web.id}"]

  attachment {
    instance     = "${aws_instance.ec2_instance[count.index].id}"
  }
}

resource "aws_network_interface_sg_attachment" "sg_attachment" {
  security_group_id    = "${data.aws_security_group.security_group.id}"
  network_interface_id = "${aws_network_interface.ec2_ami[count.index].id}"
}

答案 1 :(得分:0)

感谢Karan,您的回答为我解决了这个问题。后来,基础设施变得相当复杂,我找到了另一种更聪明的解决方法。我想与其他人分享,这可能对将来的TF社区有所帮助。

多个内部SG {内部0-7}和所有外部SG,用于创建不同的群组,从而可以在内部和外部进行选择性地通信。主要用于Microsoft HPC网格。

resource "aws_instance" "ec2_instance" {
  count                   = tonumber(var.mycount)
 vpc_security_group_ids  = [data.aws_security_group.external_security_group.id, element(data.aws_security_group.internal_security_group.*.id, count.index)]
...
}
resource "aws_security_group" "internal_security_group" {
  count       = tonumber(var.mycount)
  name        = "${var.internalSGname}${count.index}"
}
resource "aws_security_group" "external_security_group" {
  name        = ${var.external_sg_name}"

}