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

使用Terraform在GCP创建拒绝全流量及全协议端口的防火墙规则

GCP Terraform 防火墙规则相关问题解答

1. 创建不指定IP范围的拒绝所有流量的防火墙规则

在GCP中,防火墙规则若不指定source_ranges(入站规则)或destination_ranges(出站规则),默认会匹配所有IPv4和IPv6地址(等效于手动设置["0.0.0.0/0", "::/0"])。要实现拒绝所有流量的规则,只需在Terraform的google_compute_firewall资源中配置核心参数:

  • 规则动作设为action = "deny"
  • 根据需求指定direction(INGRESS或EGRESS,也可分开创建两条规则覆盖双向)
  • 不配置source_ranges(入站场景)或destination_ranges(出站场景)字段

示例配置(覆盖双向拒绝):

resource "google_compute_firewall" "deny_all_ingress" {
  name    = "deny-all-ingress"
  network = "default" # 替换为你的目标网络名称

  direction = "INGRESS"
  action    = "deny"
  priority  = 1000 # 优先级数值越小越高,需高于默认允许规则(默认优先级65535)

  deny {
    protocol = "all"
  }
}

resource "google_compute_firewall" "deny_all_egress" {
  name    = "deny-all-egress"
  network = "default"

  direction = "EGRESS"
  action    = "deny"
  priority  = 1000

  deny {
    protocol = "all"
  }
}

2. 用"all"协议替代多协议端口配置

完全可以通过设置protocol = "all"来替代逐个指定TCP/UDP及全端口的冗余配置。当协议设为all时,会涵盖所有传输层协议(包括TCP、UDP、ICMP、SCTP等),且无需指定ports字段——all协议已包含该协议下的所有端口/类型。

修改后的出站拒绝规则配置:

resource "google_compute_firewall" "deny_all_egress" {
  name    = "deny-all-egress"
  network = "default"

  direction = "EGRESS"
  action    = "deny"
  priority  = 1000

  deny {
    protocol = "all"
  }

  # 若需匹配所有目标IP,无需设置destination_ranges字段
}

该配置与你原有的TCP/UDP全端口配置效果完全一致,且更简洁,同时能覆盖原配置未包含的ICMP等协议。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 06:45:37