首页 > 解决方案 > attaching different Security Groups to different EC2s

问题描述

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.
Example:-
Group1 contains :- Head1, child :EC2-1, EC2-2....6 and need to attach SG1
Group2 contains :- Head2, child :EC2-3, EC2-4 ...6 and need to attach SG2

I don't want to write separate resource "aws_instance" Head-Module

    resource "aws_security_group" "sg" {
    count       = var.ec2_instance_count
  name        = "${local.account}${count.index}"
  vpc_id      = local.vpc_id
}

  resource "aws_instance" "ec2_instance" {
  count           = var.ec2_instance_count
  security_groups = [element(aws_security_group.sg.*.id, count.index)]
}

Child-Module:

  data "aws_security_groups" "data_security_group" {
      filter {
        name   = "group-name"
        values =  ["${local.account}${count.index}"]
      }
    }
   resource "aws_instance" "ec2_child" {
  count           = var.ec2_instance_count*var.numberofchild
  security_groups = [element(aws_security_group.data_security_group.*.id, count.index)]
}

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

on main.tf line 68, in resource "aws_instance" "ec2_instance": 68: resource "aws_instance" "ec2_instance" {

Note: I am using data "aws_security_groups" instead of data "aws_security_group". 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 data "aws_security_groups" and this error get vanished. but the latest error I m facing is: InvalidGroup.NotFound as mentioned above.

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.

标签: amazon-ec2terraformterraform-provider-awsaws-security-groupterraform0.12+

解决方案


不要使用数据,而是使用计数来创建您resource "aws_security_group"的计数resource "aws_instance",就像您可以直接引用它们一样...

resource "aws_security_group" "sg" {
  count       = var.ec2_instance_count
  name        = "${local.account}${count.index}"
  vpc_id      = local.vpc_id
}

resource "aws_instance" "ec2_instance" {
  count           = var.ec2_instance_count
  security_groups = [element(aws_security_group.sg.*.id, count.index)]
}

推荐阅读