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

Attaching AWS security group to multiple EC2 instances

我正在启动多个 Amazon EC2 实例,需要附加一个安全组。我能够为一个 EC2 实例实现它,但正在寻找多个 EC2 的解决方案。我正在使用 TerraForm 0.12。请让我知道如何使用数据资源:- data "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 the (s).提前致谢。

要删除 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}"
}

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

多个内部 SG {internal 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}"

}