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

Terraform/Terragrunt连接Minikube失败:如何获取正确主机IP?

问题:Terragrunt+Terraform无法连接Minikube集群

我已按官方文档安装并启动Minikube,集群运行正常,minikube dashboard能正常显示所有内容。但用Terragrunt封装的Terraform代码部署测试命名空间时,执行terragrunt run-all apply始终无法连接Kubernetes集群。


配置文件内容

local/terragrunt.hcl

locals {
  environment    = "dev"
  workload       = "rk"
}

inputs = {
  environment    = local.environment
  azure_region   = "local"
  workload       = local.workload
  kube_namespace = "one"

  kube_host                   = "https://172.17.0.2:55010"
  kube_client_certificate     = file("C:/Users/R/.minikube/profiles/minikube/client.crt")
  kube_client_key             = file("C:/Users/R/.minikube/profiles/minikube/client.key")
  kube_cluster_ca_certificate = file("C:/Users/R/.minikube/ca.crt")
}

remote_state {
  backend = "local"
  generate = {
    path      = "backend.tf"
    if_exists = "overwrite_terragrunt"
  }
  config = {
    path = "./terraform.tfstate"
  }
}

local/ns/terragrunt.hcl

include "environment_configration" {
  path   = find_in_parent_folders()
  expose = true
}

terraform {
  source = "../../../modules/services/azure-kubernetes-namespace///"
}

inputs = {

}

Kubernetes命名空间模块代码

provider "kubernetes" {
  host                   = "${var.kube_host}"
  client_certificate     = "${var.kube_client_certificate}"
  client_key             = "${var.kube_client_key}"
  cluster_ca_certificate = "${var.kube_cluster_ca_certificate}"
}

resource "kubernetes_namespace" "ns" {
  metadata {
    name = var.kube_namespace
  }
}

已尝试的无效方案

  • 使用minikube ip输出的IP搭配多个端口
  • 使用Windows 11中Docker Desktop显示的IP搭配多个端口
  • 使用localhost作为主机地址
  • 使用kubectl get svc获取的Kubernetes集群IP搭配多个端口

解决方案

1. 直接复用kubectl配置(推荐)

无需手动指定证书和地址,让Kubernetes Provider自动读取kubectl的配置文件,避免手动配置错误:
修改模块中的Provider配置:

provider "kubernetes" {
  config_path = "C:/Users/R/.kube/config"
}

该配置会自动加载Minikube的集群参数,包括正确的主机地址、证书等信息。

2. 手动获取准确的集群参数

如果必须手动配置,执行以下命令获取精准参数:

  • 获取kube_host:
    kubectl config view --minify -o jsonpath='{.clusters[0].cluster.server}'
    
  • 获取kube_client_certificate(解码base64内容):
    kubectl config view --minify -o jsonpath='{.users[0].user.client-certificate-data}' | base64 -d
    
  • 获取kube_client_key(解码base64内容):
    kubectl config view --minify -o jsonpath='{.users[0].user.client-key-data}' | base64 -d
    
  • 获取kube_cluster_ca_certificate(解码base64内容):
    kubectl config view --minify -o jsonpath='{.clusters[0].cluster.certificate-authority-data}' | base64 -d
    

将上述结果替换到local/terragrunt.hcl的对应字段中。

3. 确认Minikube上下文

确保当前kubectl使用的是Minikube上下文:

kubectl config use-context minikube

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 22:55:17