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

Terraform ConfigMap连接本地而非GCP问题排查与解决

解决Terraform中ConfigMap连接GKE集群而非localhost的问题

问题现象

执行terraform apply时出现以下错误:

Error: Post "http://localhost/api/v1/namespaces/default/configmaps": dial tcp [::1]:80: connect: connection refused

ConfigMap模块默认尝试连接本地Kubernetes集群,而非目标GCP GKE集群。

问题原因

ConfigMap模块未配置指向GKE集群的Kubernetes Provider,Terrafall会使用默认的localhost连接配置。

解决步骤

1. 为ConfigMap模块添加必要变量

在modules/config_map/variables.tf中添加集群相关变量:

variable "cluster_name" {
  type        = string
  description = "GKE集群名称"
}

variable "location" {
  type        = string
  description = "GKE集群所在区域/可用区"
}

2. 在ConfigMap模块中配置Kubernetes Provider

修改modules/config_map/main.tf,添加指向GKE集群的Provider配置:

# 获取GCP客户端配置
data "google_client_config" "provider" {}

# 获取GKE集群信息
data "google_container_cluster" "gke_cluster_data" {
  name     = var.cluster_name
  location = var.location
}

# 配置Kubernetes Provider指向GKE集群
provider "kubernetes" {
  host  = "https://${data.google_container_cluster.gke_cluster_data.endpoint}"
  token = data.google_client_config.provider.access_token
  cluster_ca_certificate = base64decode(
    data.google_container_cluster.gke_cluster_data.master_auth[0].cluster_ca_certificate,
  )
}

# 原ConfigMap资源定义
resource "kubernetes_config_map" "patshala_config_map" {
  metadata {
    name      = "backend-config-files"
    namespace = "default"
    labels = {
      app       = "patshala"
      component = "backend"
    }
  }

  data = {
    "patshala-service-account.json" = file(var.gcp_service_account),
    "swagger.html"                  = file(var.swagger_file_location),
    "openapi-v1.0.yaml"             = file(var.openapi_file_location)
  }
}

3. 根模块中传递必要参数给ConfigMap模块

修改根目录main.tf中的config_map模块调用,补充location参数:

module "config_map" {
  source                = "./modules/config_map"
  gcp_service_account   = var.gcp_service_account
  spec_folder           = var.spec_folder
  openapi_file_location = var.openapi_file_location
  swagger_file_location = var.swagger_file_location
  cluster_name          = module.gke_cluster.cluster_name
  location              = var.zone # 若集群为区域型则传递var.region
  depends_on            = [module.gke_cluster, module.kubernetes]
}

4. 验证权限

确保Terraform执行账号具备以下权限:

  • GKE集群的container.clusters.get权限
  • GKE集群内创建ConfigMap的权限

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 21:30:35