代码之家  ›  专栏  ›  技术社区  ›  Andrius

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

  •  0
  • Andrius  · 技术社区  · 6 年前

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

    通过这种配置,任何端口都可以用作出站/出站。但是如果我想排除一些端口,建议的方法是什么?

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

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

    1 回复  |  直到 6 年前
        1
  •  2
  •   rwisch45    6 年前

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

    这开始触及AWS安全组的限制,因为它们可以 only specify allow rules and not deny rules only have 60 inbound and 60 outbound rules per group

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

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

    然后可以用来建立 aws_security_group_rule resources 与您在问题中发布的内容类似(即从/到0-24、26-464和466-65535块)。不幸的是,这将是相当困难的,如果可能的话,会导致一种丑陋的/黑客式的方法来基于所提供的变量生成from/to端口。这是因为在Terraform的最新版本(v0.11)中不支持映射列表元素(参考 this terraform issue this one