How to add a security group depending upon count

I am using Terraform 11 version, was wondering how to add a security group that is being created depending on count variable to be added to another security group.

This works fine when count is true but run into issue when count is false.

running into same issue while using Terraform 12 version too.

Error Message : Error authorizing security group ingress rules: InvalidGroupId.Malformed: Invalid id: “” (expecting “sg-…”)

provider “aws” {
version = “>= 1.38.0”

resource “aws_security_group” “sg1” {
count = var.required_sg1 ? 1 : 0
name = “${var.env}-sg1”
vpc_id = var.vpc_id

resource “aws_security_group” “sg2” {
name = “${var.env}-sg2”
vpc_id = var.vpc_id

ingress {
from_port = 80
to_port = 80
protocol = “TCP”
security_groups = [“”]
self = true
module “test” {
source = “…/terraform/”
required_sg1 = “false”
env = “testing”
vpc_id = “vpc-xxxxx”

Hi @safdarq19!

There are two parts to this. One is that you’ve used incorrect syntax to refer to the quotes around that expression tell Terraform to treat that as a literal string rather than as a reference, and that is why the remote EC2 API is returning an error saying that the group id is malformed.

To fix that you’ll need to remove the quotes. However, because aws_security_group.sg1 has count set, that reference is a list of objects rather than a single object, and so you need to also select the specific element you want using index syntax. The easiest way to do that is to also set count in the second block:

resource "aws_security_group" "sg2" {
  count = length(aws_security_group.sg1)

  # ....

  ingress {
    # ...
    security_groups = [aws_security_group.sg1[count.index].id]

In this case there can only ever be zero or one of the first security group resource, so count.index will only every be 0 here, but using count.index here rather than a literal 0 is important to let Terraform see that that it should ignore this reference when there are no instances of aws_security_group.sg1. If you give a literal 0 then Terraform will report that the reference is invalid when there is no zeroth element.