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

Terraform防火墙规则Map变量验证问题:EGRESS规则校验失败

修正后的Terraform变量验证代码
variable "rule" {
  description = "防火墙规则集合"
  default     = {}
  type = map(object({
    policy_rule_direction = string
    match = object({
      dest_ip_ranges = list(string)
      src_ip_ranges  = list(string)
    })
  }))
  validation {
    condition = alltrue([
      for v in var.rule : 
      (v.policy_rule_direction == "INGRESS" && length(v.match.src_ip_ranges) > 0) ||
      (v.policy_rule_direction == "EGRESS" && length(v.match.dest_ip_ranges) > 0)
    ])
    error_message = "规则校验失败:INGRESS规则必须指定非空的src_ip_ranges;EGRESS规则必须指定非空的dest_ip_ranges。"
  }
}

关键修改说明

  • 多方向适配校验:通过逻辑或(||)分支分别处理两种规则方向,确保INGRESS校验源IP范围、EGRESS校验目标IP范围,解决原代码仅适配单一方向的问题
  • 非空判断优化:用length(...) > 0替代!=null,因为空列表([])本身不为null,但属于业务无效配置,该判断更贴合实际需求
  • 错误信息明确化:在报错内容中区分两种方向的要求,便于快速定位配置问题

如果需要限制规则方向只能是INGRESS或EGRESS,可追加方向有效性校验:

validation {
  condition = alltrue([
    for v in var.rule : 
    contains(["INGRESS", "EGRESS"], v.policy_rule_direction) && (
      (v.policy_rule_direction == "INGRESS" && length(v.match.src_ip_ranges) > 0) ||
      (v.policy_rule_direction == "EGRESS" && length(v.match.dest_ip_ranges) > 0)
    )
  ])
  error_message = "规则校验失败:规则方向只能是INGRESS或EGRESS;INGRESS规则必须指定非空的src_ip_ranges;EGRESS规则必须指定非空的dest_ip_ranges。"
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 07:52:14