Home > Net >  How do I create 3 separate security groups from 1 security group resource block?
How do I create 3 separate security groups from 1 security group resource block?

Time:07-05

Right now I have a bastion host in 3 separate public subnets and they all share the same security group. However, I would like to create 3 separate security groups, one for each bastion host that gets created. I have 1 resource block that creates 3 bastion hosts total (1 for each subnet), is there any way I can create a separate security group for each of them. utilizing just one security group resource block?

bastion.tf

resource "aws_instance" "bastion" {
  count           = var.azs
  ami             = data.aws_ami.AL2_ami.id
  key_name        = aws_key_pair.bastion_auth.id
  instance_type   = var.instance_type
  security_groups = [aws_security_group.bastion-sg.id]

  associate_public_ip_address = true
  subnet_id                   = module.vpc.public_subnets[count.index]
  user_data                   = file("userdata.tpl")

  root_block_device {
    volume_size = var.main_vol_size
  }

  tags = {
    Name = "${var.name}-bastion-host-${count.index   1}"
  }
}

resource "aws_security_group" "bastion-sg" {

  name   = "bastion-security-group"
  vpc_id = module.vpc.vpc_id

  ingress {
    protocol    = "tcp"
    from_port   = 22
    to_port     = 22
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    protocol    = -1
    from_port   = 0
    to_port     = 0
    cidr_blocks = ["0.0.0.0/0"]
  }
}

Error after making changes:

Error: expected metadata_options.0.instance_metadata_tags to be one of [disabled enabled], got coalfire-bastion-1
│
│   on node-group.tf line 40, in resource "aws_security_group" "node-sg":
│   40:     security_groups = [aws_security_group.bastion-sg.id]
│
│ Because aws_security_group.bastion-sg has "count" set, its attributes must be accessed on specific instances.
│
│ For example, to correlate with indices of a referring resource, use:
│     aws_security_group.bastion-sg[count.index]

CodePudding user response:

You would want to add the same count = var.azs to the security group resource as well:

resource "aws_security_group" "bastion-sg" {
  count  = var.azs
  name   = "bastion-security-group-${count.index}"
  vpc_id = module.vpc.vpc_id

  ingress {
    protocol    = "tcp"
    from_port   = 22
    to_port     = 22
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    protocol    = -1
    from_port   = 0
    to_port     = 0
    cidr_blocks = ["0.0.0.0/0"]
  }
}

For the bastion host, you may want to use the count.index to refer to a security group:

resource "aws_instance" "bastion" {
  count           = var.azs
  # ...
  security_groups = [aws_security_group.bastion-sg[count.index].id]
  
  # ...
}

This will create 3 identical security group for each bastion host. Please note, you can not have the same name for each security group. To overcome this limitation, you can add the count.index to the name of the SG as well.

  • Related