通过Terraform安装GKE及Anthos的依赖配置与报错问题咨询
解决方案:Terraform部署GKE后自动执行Anthos Hub与ASM的依赖配置
问题根因
- 初始报错连接GKE APIServer被拒绝,是因为GKE集群、节点池创建完成后,K8s APIServer和节点还需要一段时间完成初始化,ASM和Hub模块提前执行导致访问失败
- 直接给ASM/Hub模块添加节点池的
depends_on后出现count报错,是因为ASM模块内部的random_id.cache资源的count值依赖了local.skip_download,该值如果关联了动态生成的集群属性,Terraform在计划阶段无法确定count值,就会抛出异常
正确配置方案
通过显式添加集群就绪检查资源,让后续依赖模块等待集群完全可用后再执行,同时固定ASM模块的动态参数避免count计算异常。
步骤1:新增GKE集群就绪检查资源
添加null_resource资源,通过命令行主动等待APIServer和所有节点就绪:
resource "null_resource" "gke_cluster_ready" { # 先等待集群和节点池创建完成 depends_on = [ module.gke, module.gke_node_pool11, module.gke_node_pool_preemptible22 ] provisioner "local-exec" { command = <<EOT # 拉取集群凭证 gcloud container clusters get-credentials ${module.gke.name} --location ${module.gke.location} --project ${var.project_id} # 等待APIServer可访问 until kubectl cluster-info; do sleep 10; done # 等待所有节点进入Ready状态 kubectl wait --for=condition=Ready nodes --all --timeout=600s EOT } triggers = { cluster_id = module.gke.id } }
步骤2:修改Hub和ASM模块的依赖配置
让两个模块依赖就绪检查资源,同时显式固定ASM的skip_download参数避免count动态计算:
module "hub-primary" { source = "terraform-google-modules/kubernetes-engine/google//modules/hub" project_id = var.project_id cluster_name = module.gke.name cluster_endpoint = module.gke.endpoint location = module.gke.location gke_hub_membership_name = "primary" gke_hub_sa_name = "primary" # 等待集群就绪后执行 depends_on = [null_resource.gke_cluster_ready] } module "asm" { source = "github.com/terraform-google-modules/terraform-google-kubernetes-engine//modules/asm" cluster_name = module.gke.name cluster_endpoint = module.gke.endpoint project_id = var.project_id location = module.gke.location enable_all = true enable_cluster_roles = true enable_cluster_labels = false enable_gcp_apis = true enable_gcp_iam_roles = false enable_gcp_components = true enable_registration = false asm_version = "1.10" managed_control_plane = false options = ["envoy-access-log,egressgateways"] skip_validation = false outdir = "./${module.gke.name}-outdir-${var.asm_version}" # 显式固定参数,避免动态计算count skip_download = false # 等待集群就绪后执行 depends_on = [null_resource.gke_cluster_ready] }
注意事项
- 运行Terraform的环境需要提前安装
gcloud和kubectl命令行工具,并且完成gcloud身份认证,拥有GKE集群的访问权限 - 如果是私有GKE集群,需要将运行Terraform的机器的公网IP添加到GKE APIServer的授权访问列表,否则会持续报连接被拒绝的错误
- 如果仍出现count相关报错,可以将ASM模块的
outdir参数改为固定字符串,不要引用module.gke.name这类运行时才确定的属性,避免动态值传递导致count计算异常
内容的提问来源于stack exchange,提问作者Sanjay M. P.
相关产品推荐
相关产品推荐

