在Google Cloud中创建自定义网络与Cloud SQL服务连接报错求助
问题排查与修复
错误根源
你遇到的报错是:The reserved_peering_ranges field must be the name of an allocated address range, not an IP CIDR range.
问题出在google_service_networking_connection资源的reserved_peering_ranges参数配置上——该参数要求传入已分配的全球地址资源名称,但你当前直接使用了子网的CIDR段,不符合GCP服务 peering的规则。
修复步骤与代码调整
1. 为服务Peering添加预留地址资源
在你的网络模块代码中,新增google_global_address资源,专门分配用于服务 peering 的IP范围:
resource "google_compute_network" "vpc_network" { name = "terraform-network" auto_create_subnetworks = false routing_mode = "REGIONAL" } resource "google_compute_subnetwork" "my_subnets" { count = var.subnet_count name = var.subnet_names[count.index] network = google_compute_network.vpc_network.name region = var.region ip_cidr_range = cidrsubnet(var.vpc_cidr, 8, count.index) } # 新增:创建服务Peering专用的预留地址范围 resource "google_global_address" "private_peering_range" { name = "private-peering-range" purpose = "VPC_PEERING" address_type = "INTERNAL" prefix_length = 16 # 根据你的VPC CIDR调整,确保不与子网范围重叠 network = google_compute_network.vpc_network.self_link } resource "google_service_networking_connection" "private_service_connection" { network = google_compute_network.vpc_network.name service = "servicenetworking.googleapis.com" # 修改为引用预留地址资源的名称,而非子网CIDR reserved_peering_ranges = [google_global_address.private_peering_range.name] depends_on = [google_compute_subnetwork.my_subnets] } # 确保输出VPC的self_link供Cloud SQL模块调用 output "vpc_network_self_link" { value = google_compute_network.vpc_network.self_link }
2. 关键配置说明
google_global_address的purpose必须设为VPC_PEERING,这样GCP会将该地址范围预留给服务 peering 使用。- 调整
prefix_length和地址范围时,要确保其不与你的VPC子网CIDR重叠,避免IP冲突。 reserved_peering_ranges必须传入地址资源的name属性,而非CIDR字符串。
额外检查
- 确认网络模块的
output "vpc_network_self_link"已正确配置,这样Cloud SQL模块的custom_network = module.network.vpc_network_self_link才能正常引用。 - 确保Cloud SQL模块中配置的私有网络关联逻辑正确,依赖关系
depends_on = [module.network]已生效。
内容的提问来源于stack exchange,提问作者Hardik Patel
相关产品推荐
相关产品推荐

