5

I'm testing Terraform/Terragrunt to deploy RDS DB to AWS.

Is there a way to add conditional ingress to the aws_security_group definitions?

Terraform v0.12.3 Terragrunt version v0.19.8

As now the best I was able to do was add one security group for each condition, each with a count statement, and add all the single security groups to the DB instance, like

resource "aws_security_group" "db_sg_office" {
      ...
      count = var.publicly_accessible ? 1 : 0
      
      ingress {
        ...
        cidr_blocks = ["1.2.3.4/32"]
      }    
}

...
    
resource "aws_db_instance" "default" {
  ...
  vpc_security_group_ids = [ ... , "${aws_security_group.db_sg_office.id}" , ...]
  ...
}

This is actually NOT working and fails when the security group is referenced in the DB resource.

dur
  • 15,689
  • 25
  • 79
  • 125

1 Answers1

6

On terraform try to use aws_security_group_rule resource with count parameter, for additional reference read documentation


resource "aws_security_group" "db_sg_office" {
  ...
}

resource "aws_security_group_rule" "open_public" {
  security_group_id = aws_security_group.db_sg_office.id
  count     = var.publicly_accessible ? 1 : 0
  type      = "ingress"
  from_port = 0
  to_port   = 65535
  cidr_blocks = ["1.2.3.4/32"]
  protocol  = "tcp"
}
avivamg
  • 12,197
  • 3
  • 67
  • 61
RyanKim
  • 1,557
  • 9
  • 10