【问题标题】:Terraform - allow all outbound ports except specific ports?Terraform - 允许除特定端口之外的所有出站端口?
【发布时间】:2019-03-18 22:45:46
【问题描述】:

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

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

假设我想排除端口 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"]
  }

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

【问题讨论】:

  • 很确定,你不能 ;-( 如果你有很多排除项,你可以编写一个包装脚本来吐出所需的 TF 代码,但是根据端口的数量,你可能最终达到每个 SG 的最大规则数。

标签: terraform terraform-provider-aws


【解决方案1】:

例如,我可以定义规则以允许所有端口,然后排除一些

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

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

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

然后可用于构建aws_security_group_rule resources,类似于您在问题中发布的内容(即从/到 0-24、26-464 和 466-65535 的块)。不幸的是,这将是相当困难的,并且如果可能的话,会导致基于提供的变量生成从/到端口的丑陋/骇人听闻的方式。这是因为最新 (v0.11) 版本的 Terraform(参考 this terraform issuethis one)目前不支持列表元素的映射,但 Terraform v0.12 将使这些类型的操作更容易。

【讨论】:

    猜你喜欢
    • 2020-11-04
    • 1970-01-01
    • 1970-01-01
    • 2018-02-07
    • 2019-01-21
    • 1970-01-01
    • 2019-06-23
    • 2017-02-10
    • 2023-03-09
    相关资源
    最近更新 更多