Different aws_security_group egress rules depending on user-input (terraform)

43 Views Asked by At

I am trying to figure out how to have different egress rules depending on the variable supplied. For my use case, the security group should either have full outbound access to the world, or be removed entirely.

Currently I am manually commenting out one rule versus the other when I need to make these changes but ideally I'd like to control this by using a variable or some other user-supplied means.

When I need egress open to the world:

  resource "aws_security_group" "test" {
    ...
    egress {
      from_port        = 0
      to_port          = 0
      protocol         = "-1"
      cidr_blocks      = ["0.0.0.0/0"]
      ipv6_cidr_blocks = ["::/0"]
    }
    ...

When I need all egress rules removed entirely:


  resource "aws_security_group" "test" {
    ...
    egress = []
    ...
1

There are 1 best solutions below

1
Marcin On BEST ANSWER

It would be best to use aws_security_group_rule and count:

variable "enable_egress" {
  type = bool
  default = true
}


resource "aws_security_group" "test" {

}

resource "aws_security_group_rule" "example" {

  security_group_id = aws_security_group.test.id

  count = var.enable_egress == true ? 1 : 0

  type              = "egress"
  from_port        = 0
  to_port          = 0
  protocol         = "-1"
  cidr_blocks      = ["0.0.0.0/0"]
  ipv6_cidr_blocks = ["::/0"] 
}