Terraform - 允许除特定端口外的所有出站端口?

Terraform - allow all outbound ports except specific ports?

我在 terraform 中定义了这个 AWS 安全组:

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

使用此配置,任何端口都可以用作 outgoing/outbound。但是如果我想排除一些端口,推荐的方法是什么?

假设我想排除端口 25 和 465,所以我可以做类似的事情(而不是使用允许任何端口的出口规则):

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

但这需要定义特定的范围,这需要定义一些额外的出口规则。也许有更好的方法吗?例如,我可以在哪里定义规则以允许所有端口然后排除一些端口?

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

这开始触及 AWS 安全组的限制,因为它们可以 only specify allow rules and not deny rules, and you can only have 60 inbound and 60 outbound rules per group(每个总共 120 条规则)。

理想情况下,您可以像这样定义一个变量

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

然后可用于构建 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),但 Terraform v0.12 将使这些类型的操作更加容易。