2
votes

Having an issue creating a conditional resource based on a variable that's evaluated and used to influence a count in the resource. The issue is that the conditionally created resource is then referred to in other places in the code. For example, this security group:

resource "aws_security_group" "mygroup" {
  count       = var.deploy_mgroup ? 1 : 0
  name        = "mygroup-sg"
  vpc_id      = aws_vpc.main.id

  ingress {
    description = "Allow something."
    from_port   = 8111
    to_port     = 8111
    protocol    = "tcp"
    security_groups = [aws_security_group.anothergroup.id]

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

Then this is referred to in another group:

resource "aws_security_group" "rds" {
  name        = "rds-sg"
  vpc_id      = aws_vpc.main.id
  
  ingress {
    description = "Allow PGSQL"
    from_port       = 5432
    to_port         = 5432
    protocol        = "tcp"
    cidr_blocks     = [var.ingress_src_ip]
    security_groups = [aws_security_group.mygroup[0].id,aws_security_group.anothergroup.id]
  }

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

So in this case I recognise that the resource using count has to be referenced as a list, which works OK if the variable deploy_mgroup is set to true. If it's set to false, the resource that has the count is obviously never created, so the list that the second group refers to aws_security_group.mygroup[0].id is empty, which throws me an error.

I'm not sure what I need to do here, maybe this is just a bad approach and there's something better I should be using? I haven't used Terraform for quite a while and I've missed a few versions.

Any pointers would be appreciated!

Thanks

1

1 Answers

2
votes

I hastly read your post, and I had no time to try the solution I am going to suggest. For that reason: sorry! :)

I suggest you to change:

security_groups = [aws_security_group.mygroup[0].id,aws_security_group.anothergroup.id]

to

security_groups = var.deploy_mgroup ? [aws_security_group.mygroup[0].id,aws_security_group.anothergroup.id] : null

Errata Corrige:

I suggest you to change:

security_groups = [aws_security_group.mygroup[0].id,aws_security_group.anothergroup.id]

to

security_groups = 
      var.deploy_mgroup 
    ? [aws_security_group.mygroup[0].id, aws_security_group.anothergroup.id] 
    : [aws_security_group.anothergroup.id]