title: attaching different Security Groups to different EC2s
body: <p>Requirement:-
  I have multiple group(say 2 groups) of EC2s where each group contain 6 EC2. and I have to attach different SG to each group.<br />
  Example:-<br />
  Group1 contains :- Head1, child :EC2-1, EC2-2....6  and need to attach SG1<br />
  Group2 contains :- Head2, child :EC2-3, EC2-4  ...6 and need to attach SG2</p>
  <p><strong>I don't want to write separate resource &quot;aws_instance&quot;</strong>
  Head-Module</p>
  <pre><code>    resource &quot;aws_security_group&quot; &quot;sg&quot; {
      count       = var.ec2_instance_count
    name        = &quot;${local.account}${count.index}&quot;
    vpc_id      = local.vpc_id
  }
  
    resource &quot;aws_instance&quot; &quot;ec2_instance&quot; {
    count           = var.ec2_instance_count
    security_groups = [element(aws_security_group.sg.*.id, count.index)]
  }
  </code></pre>
  <p>Child-Module:</p>
  <pre><code>  data &quot;aws_security_groups&quot; &quot;data_security_group&quot; {
        filter {
          name   = &quot;group-name&quot;
          values =  [&quot;${local.account}${count.index}&quot;]
        }
      }
     resource &quot;aws_instance&quot; &quot;ec2_child&quot; {
    count           = var.ec2_instance_count*var.numberofchild
    security_groups = [element(aws_security_group.data_security_group.*.id, count.index)]
  }
  </code></pre>
  <p>Error: Error launching source instance: InvalidGroup.NotFound: The security group 'terraform-2020082
  4151444795600000001' does not exist in VPC 'vpc-ghhje85abcy'
  status code: 400, request id: 9260fd88-a03a-4c46-b67c-3287594cdab5</p>
  <p>on main.tf line 68, in resource &quot;aws_instance&quot; &quot;ec2_instance&quot;:
  68: resource &quot;aws_instance&quot; &quot;ec2_instance&quot; {</p>
  <p>Note: I am using <code>data &quot;aws_security_groups&quot;</code> instead of <code>data &quot;aws_security_group&quot;</code>. If I use the later one, I know I will be able to get only one SG in the data resource and it throws me an error :multiple Security Groups matched;  from which I kind of moved ahead by using <code>data &quot;aws_security_groups&quot;</code> and this error get vanished. but the latest error I m facing is: InvalidGroup.NotFound as mentioned above.</p>
  <p>Update: I am able to use data resource and able to attach the different SG to different EC2. the only issue is random Sequencing.  for all 6 EC2 of group 1 I want them to assign first SG and so on.</p>