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

如何用Terraform for循环生成aws_security_group所需的ingress安全组规则

错误原因

你的草稿代码多嵌套了一层冗余循环:local.subnets本身就是存储每个子网属性的对象列表,直接遍历列表元素即可,无需对单个子网对象做二次遍历,也不需要用flatten函数做扁平化处理。

正确循环写法

locals {
  # 你原来的子网定义
  subnets = [
    {
      availability_zone = "us-east-1a"
      cidr_block = "10.0.0.0/23"
    },
    {
      availability_zone = "us-east-1b"
      cidr_block = "10.0.2.0/23"
    },
    {
      availability_zone = "us-east-1c"
      cidr_block = "10.0.4.0/23"
    }
  ]

  # 修正后的安全组规则生成代码
  ingress_rules = [
    for subnet in local.subnets : {
      description               = subnet.availability_zone
      type                      = "ingress"
      from_port                 = 0
      to_port                   = 0
      protocol                  = "-1"
      cidr_blocks               = [subnet.cidr_block]
      ipv6_cidr_blocks          = []
      prefix_list_ids           = []
      security_groups           = []
      self                      = false
    }
  ]
}

注:from_port和to_port建议使用数字类型而非字符串,符合AWS Provider的参数类型要求。

传入安全组资源示例

通过dynamic块把生成的规则传入aws_security_group资源:

resource "aws_security_group" "this" {
  name        = "subnet-ingress-sg"
  vpc_id      = var.vpc_id

  dynamic "ingress" {
    for_each = local.ingress_rules
    content {
      description      = ingress.value.description
      from_port        = ingress.value.from_port
      to_port          = ingress.value.to_port
      protocol         = ingress.value.protocol
      cidr_blocks      = ingress.value.cidr_blocks
      ipv6_cidr_blocks = ingress.value.ipv6_cidr_blocks
      prefix_list_ids  = ingress.value.prefix_list_ids
      security_groups  = ingress.value.security_groups
      self             = ingress.value.self
    }
  }

  # 按需配置出网规则,此处为默认全通示例
  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 07:06:03