Search code examples
amazon-ec2terraformterragrunt

aws_security_group - conditional ingress


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.


Solution

  • 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"
    }