Search code examples
amazon-ec2terraformterraform-provider-awsaws-security-groupterraform0.12+

Attaching AWS security group to multiple EC2 instances


I am spinning up multiple Amazon EC2 instances and need to attach a Security Group. I am able to achieve it for one EC2 instance but looking for solution for multiple EC2s. I am using TerraForm 0.12. Please let me know how can I use data resource :- data "aws_instances" (s).

Here is the code for single EC2 which i am trying to convert for multiple EC2s:

    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.
    }

I want to achieve this using data "aws_instances" #notice the (s). Thanks in advance.


Solution

  • For removing the Hard coding of ec2 AMI, you can use the following data provider:-

      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",
        ]
      }
    }
    

    For rendering the ami id:-

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

    For getting 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}"
    }