1
votes

I have this AWS security group defined in terraform:

resource "aws_security_group" "sg" {
  name = "${var.name}"
  description = "${var.description}"
  vpc_id = "${data.terraform_remote_state.vpc.vpc_id}"

  ingress {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  ingress {
    from_port   = 443
    to_port     = 443
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  ingress {
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["${var.ext_blocks}"]
  }

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

With this configartion, any port can be used as outgoing/outbound. But if I want to exclude some ports, what would be the recommended way?

Let say I want to exclude ports 25 and 465, so I could do something like (instead of using that one egress rule that allows any port):

  egress {
    from_port       = 0
    to_port         = 24
    protocol        = "-1"
    cidr_blocks     = ["0.0.0.0/0"]
  }
  egress {
    from_port       = 26
    to_port         = 464
    protocol        = "-1"
    cidr_blocks     = ["0.0.0.0/0"]
  }
  egress {
    from_port       = 466
    to_port         = 65535
    protocol        = "-1"
    cidr_blocks     = ["0.0.0.0/0"]
  }

But this needs to define specific ranges, which require to define some extra egress rules. Is there a better way maybe? For example where I can define rule to allow all ports and then exclude some?

1
Pretty sure, you can't ;-( If you have lots of exclusions, you could write a wrapper script that would spit out the required TF code, but then depending on how many ports, you might end up hitting the max # of rules per SG. - KJH

1 Answers

2
votes

For example where I can define rule to allow all ports and then exclude some

This starts hitting the limitation of AWS security groups because they can only specify allow rules and not deny rules, and you can only have 60 inbound and 60 outbound rules per group (total of 120 rules each).

Ideally, you'd be able to define a variable like this

variable "excluded_ports" { default=[25,465] }

that could then be used to build up aws_security_group_rule resources similar to what you posted in your question (i.e from/to blocks of 0-24, 26-464, and 466-65535). Unfortunately, that would be fairly difficult and, if possible, result in an ugly/hackish way to generate the from/to ports based off of that provided variable. This is because mapping over list elements is not currently supported in the latest (v0.11) version of Terraform (ref this terraform issue and this one), but Terraform v0.12 will make those types of operations much easier.