使用 "null_resource" "apply" 执行时的 Terraform "file name too long"

Terraform "file name too long" when executing with "null_resource" "apply"

我正在尝试执行以下命令: kubectl get cm aws-auth -n kube-system -o json | jq --arg add "`cat additional_roles_aws_auth.yaml`" '.data.mapRoles += $add' | kubectl apply -f - 作为本地 Terraform 执行的一部分,如下所示:

locals {
  kubeconfig = yamlencode({
    apiVersion      = "v1"
    kind            = "Config"
    current-context = "terraform"
    clusters = [{
      name = module.eks.cluster_id
      cluster = {
        certificate-authority-data = module.eks.cluster_certificate_authority_data
        server                     = module.eks.cluster_endpoint
      }
    }]
    contexts = [{
      name = "terraform"
      context = {
        cluster = module.eks.cluster_id
        user    = "terraform"
      }
    }]
    users = [{
      name = "terraform"
      user = {
        token = data.aws_eks_cluster_auth.this.token
      }
    }]
  })
}
resource "null_resource" "apply" {
  triggers = {
    kubeconfig = base64encode(local.kubeconfig)
    cmd_patch  = <<-EOT
      kubectl get cm aws-auth -n kube-system -o json | jq --arg add "`cat additional_roles_aws_auth.yaml`" '.data.mapRoles += $add' | kubectl apply -f -
    EOT
  }
    provisioner "local-exec" {
    interpreter = ["/bin/bash", "-c"]
    environment = {
      KUBECONFIG = self.triggers.kubeconfig
    }
    command = self.triggers.cmd_patch
  }
}

在 Terraform 之外执行相同的命令,显然在命令行上工作正常。 但是,作为 Terraform 脚本的一部分执行时,我总是会收到以下错误:

│ ': exit status 1. Output:
│ iAic2FtcGxlLWNsdXN0ZXI...WaU5ERXdNekEiCg==":
│ open
│ ImFwaVZlcnNpb24iOiAidjEiy...RXdNekEiCg==:
│ file name too long

有人知道问题出在哪里吗?

根据我的评论:KUBECONFIG 环境变量需要是配置文件列表而不是文件本身的内容 [1]:

The KUBECONFIG environment variable is a list of paths to configuration files.

最初的问题是文件的内容以 base64 格式 [2] 编码,并且之前没有解码就以该格式使用。值得庆幸的是,Terraform 具有这两个功能 built-in,因此使用 base64decode [3] 将 return “正常”文件内容。不过,它将是 文件内容 而不是 配置文件 的路径。根据其他评论,我想需要注意的重要一点是 additional_roles_aws_auth.yaml 文件必须与根模块位于同一目录中。由于命令有点复杂,我不确定您是否可以使用 Terraform built-in path object [4] 来确保在模块的根目录中搜索文件:

kubectl get cm aws-auth -n kube-system -o json | jq --arg add "`cat ${path.root}/additional_roles_aws_auth.yaml`" '.data.mapRoles += $add' | kubectl apply -f -

[1] https://kubernetes.io/docs/tasks/access-application-cluster/configure-access-multiple-clusters/#set-the-kubeconfig-environment-variable

[2]https://www.terraform.io/language/functions/base64encode

[3]https://www.terraform.io/language/functions/base64decode

[4]https://www.terraform.io/language/expressions/references#filesystem-and-workspace-info