You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Terraform中为端口范围创建AWS安全组?

解决方案

你错误地将端口范围写在了单个from_port/to_port字段中,Terraform会把4011-4999解析为减法运算(结果为-988),这完全不符合需求。AWS安全组的端口范围是通过分别指定**起始端口(from_port)和结束端口(to_port)**来定义的,以下是两种实现方式:

基础正确配置

直接在ingress块中分别设置from_port为范围起始值、to_port为范围结束值即可:

resource "aws_security_group" "sg_nx" {
  name   = "sg_nx"
  vpc_id = aws_vpc.vpc.id

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

  # 正确配置UDP端口范围4011-4999
  ingress {
    from_port   = 4011  # 端口范围起始值
    to_port     = 4999  # 端口范围结束值
    protocol    = "udp"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

动态生成规则的实现

如果需要批量管理多个端口规则,可使用Terraform的dynamic块结合变量实现动态生成,便于后续维护:

1. 定义规则变量

先定义一个包含所有入站规则的变量(也可使用本地值locals替代):

variable "ingress_rules" {
  type = list(object({
    from_port   = number
    to_port     = number
    protocol    = string
    cidr_blocks = list(string)
  }))
  default = [
    {
      from_port   = 4000
      to_port     = 4000
      protocol    = "tcp"
      cidr_blocks = ["0.0.0.0/0"]
    },
    {
      from_port   = 4011
      to_port     = 4999
      protocol    = "udp"
      cidr_blocks = ["0.0.0.0/0"]
    }
  ]
}

2. 使用dynamic块生成规则

通过dynamic "ingress"遍历变量中的规则,自动生成对应的入站规则:

resource "aws_security_group" "sg_nx" {
  name   = "sg_nx"
  vpc_id = aws_vpc.vpc.id

  dynamic "ingress" {
    for_each = var.ingress_rules
    content {
      from_port   = ingress.value.from_port
      to_port     = ingress.value.to_port
      protocol    = ingress.value.protocol
      cidr_blocks = ingress.value.cidr_blocks
    }
  }
}

后续添加或修改规则时,只需调整var.ingress_rules中的列表项即可,无需修改资源块本身,适合规则数量较多的场景。

内容的提问来源于stack exchange,提问作者Alexander Borochkin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 05:27:23