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

使用null_resource与local_file传递EKS端点至Kubernetes Provider报错求助

问题分析

错误里的URL包含重复前缀、双引号和换行符,根源在于:

  • aws eks describe-cluster的--query输出默认是带双引号的JSON格式,直接写入文件会保留引号
  • 使用>>追加写入文件,多次执行会导致内容重复
  • 文件名不匹配(null_resource写入output.txt,但local_file读取outputtxt)
  • depends_on引用的null_resource名称错误
修正后的代码(按你要求的null_resource+local_file方案)

1. 修正null_resource端点获取逻辑

resource "null_resource" "endpoint" {
  triggers = {
    build_number = timestamp()
  }
  provisioner "local-exec" {
    # 用>覆盖文件避免重复内容,--output text去掉JSON引号和格式,输出纯端点字符串
    command = "aws eks describe-cluster --name ${var.cluster_name} --query cluster.endpoint --output text > ${path.module}/output.txt"
  }
}

2. 修正local_file读取与Provider配置

data "local_file" "output" {
  filename   = "${path.module}/output.txt" # 修正文件名匹配
  depends_on = [null_resource.endpoint] # 修正依赖资源名称
}

provider "kubernetes" {
  host                   = trimspace(data.local_file.output.content) # 用trimspace去除多余换行/空格
  cluster_ca_certificate = base64decode(trimspace(data.local_file.ca_cert.content)) # 需单独获取CA证书,见下方补充
  exec {
    command     = "aws"
    args        = ["eks", "get-token", "--cluster-name", "${var.cluster_name}"] # 变量添加引号避免语法错误
  }
}

补充:CA证书的单独获取

如果需要CA证书,需新增对应的null_resource和local_file:

resource "null_resource" "ca_cert" {
  triggers = {
    build_number = timestamp()
  }
  provisioner "local-exec" {
    command = "aws eks describe-cluster --name ${var.cluster_name} --query cluster.certificateAuthority.data --output text > ${path.module}/ca_cert.txt"
  }
}

data "local_file" "ca_cert" {
  filename   = "${path.module}/ca_cert.txt"
  depends_on = [null_resource.ca_cert]
}
更可靠的替代方案(无需本地文件中转)

直接用Terraform的AWS数据源获取集群信息,避免文件操作的潜在问题:

data "aws_eks_cluster" "this" {
  name = var.cluster_name
}

provider "kubernetes" {
  host                   = data.aws_eks_cluster.this.endpoint
  cluster_ca_certificate = base64decode(data.aws_eks_cluster.this.certificate_authority.0.data)
  exec {
    command     = "aws"
    args        = ["eks", "get-token", "--cluster-name", var.cluster_name]
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 02:22:50