使用Terraform无法连接AWS EKS Kubernetes集群求助
AWS EKS部署时kubeconfig YAML解析错误排查
问题现象
使用Terraform部署AWS EKS集群,执行命令terraform output kubeconfig > ~/.kube/config后,运行kubectl cluster-info等任意kubectl命令,均触发以下错误:
error loading config file, yaml: line 4: mapping values are not allowed in this context
用户提供的outputs.tf代码如下:
# Outputs # locals { config_map_aws_auth = <<CONFIGMAPAWSAUTH apiVersion: v1 kind: ConfigMap metadata: name: aws-auth namespace: kube-system data: mapRoles: | - rolearn: ${aws_iam_role.demo-node.arn} username: system:node:{{EC2PrivateDNSName}} groups: - system:bootstrappers - system:nodes CONFIGMAPAWSAUTH kubeconfig = <<KUBECONFIG apiVersion: v1 clusters: - cluster: server: ${aws_eks_cluster.demo.endpoint} certificate-authority-data: ${aws_eks_cluster.demo.certificate_authority[0].data} name: kubernetes contexts: - context: cluster: kubernetes user: aws name: aws current-context: aws kind: Config preferences: {} users: - name: aws user: exec: apiVersion: client.authentication.k8s.io/v1beta1 command: aws-iam-authenticator args: - "token" - "-i" - "${var.cluster-name}" KUBECONFIG } output "config_map_aws_auth" { value = local.config_map_aws_auth } output "kubeconfig" { value = local.kubeconfig }
错误原因
- kubeconfig heredoc开头多余空行:
<<KUBECONFIG之后的空行会被直接写入生成的kubeconfig文件,导致YAML解析器在处理开头空行后的内容时出现格式识别错误。 - 转义引号错误:
args中的"是HTML转义字符,Terraform会直接将其输出到kubeconfig文件中,而非解析为YAML所需的双引号,破坏了YAML格式。
修复方案
修改outputs.tf中的kubeconfig定义,移除开头多余空行,并将转义引号替换为普通双引号:
# Outputs # locals { config_map_aws_auth = <<CONFIGMAPAWSAUTH apiVersion: v1 kind: ConfigMap metadata: name: aws-auth namespace: kube-system data: mapRoles: | - rolearn: ${aws_iam_role.demo-node.arn} username: system:node:{{EC2PrivateDNSName}} groups: - system:bootstrappers - system:nodes CONFIGMAPAWSAUTH kubeconfig = <<KUBECONFIG apiVersion: v1 clusters: - cluster: server: ${aws_eks_cluster.demo.endpoint} certificate-authority-data: ${aws_eks_cluster.demo.certificate_authority[0].data} name: kubernetes contexts: - context: cluster: kubernetes user: aws name: aws current-context: aws kind: Config preferences: {} users: - name: aws user: exec: apiVersion: client.authentication.k8s.io/v1beta1 command: aws-iam-authenticator args: - "token" - "-i" - "${var.cluster-name}" KUBECONFIG } output "config_map_aws_auth" { value = local.config_map_aws_auth } output "kubeconfig" { value = local.kubeconfig }
验证步骤
- 重新执行Terraform应用:
terraform apply - 重新导出kubeconfig文件:
terraform output kubeconfig > ~/.kube/config - 测试集群连通性:
kubectl cluster-info
内容的提问来源于stack exchange,提问作者Igorek
相关产品推荐
相关产品推荐

