Terraform销毁K8s autoscaler资源失败 报invalid apiVersion错误
问题背景
长期使用如下Terraform代码片段管理EKS集群的cluster-autoscaler自动扩缩容组件:
resource "helm_release" "cluster-autoscaler" { depends_on = [ module.eks ] name = "cluster-autoscaler" namespace = local.k8s_service_account_namespace repository = "https://kubernetes.github.io/autoscaler" chart = "cluster-autoscaler" version = "9.10.7" create_namespace = false }
该配置在Gitlab CI/CD流水线中已稳定运行数月,近期执行时突然抛出如下错误:
module.review_vpc.helm_release.cluster-autoscaler: Refreshing state... [id=cluster-autoscaler] ╷ │ Error: Kubernetes cluster unreachable: exec plugin: invalid apiVersion "client.authentication.k8s.io/v1alpha1" │ │ with module.review_vpc.helm_release.cluster-autoscaler, │ on ..\..\modules\aws\eks.tf line 319, in resource "helm_release" "cluster-autoscaler": │ 319: resource "helm_release" "cluster-autoscaler" {
当前集群环境为Kubernetes 1.21版本AWS EKS,使用的Terraform provider配置如下:
terraform { required_providers { aws = { source = "hashicorp/aws" version = "~> 3.0" } kubectl = { source = "gavinbunney/kubectl" version = "1.14.0" } } }
后续补充使用的EKS Terraform模块配置:
module "eks" { source = "terraform-aws-modules/eks/aws" version = "17.24.0" }
报错根因
报错核心是Kubernetes客户端认证API版本不兼容:
- 当前使用的3.x版本AWS provider、17.24.0版本EKS Terraform模块,生成的kubeconfig默认指定的认证API版本为
client.authentication.k8s.io/v1alpha1,该版本早已被官方弃用。 - 之前流水线稳定运行是因为CI环境内的kubectl、Helm、AWS CLI版本较旧,仍兼容该旧API;近期CI运行环境的依赖包自动迭代升级后,新版本客户端彻底移除了对v1alpha1认证API的支持,因此原有配置无变更的情况下突然执行失败。
- 使用的1.14.0版本
gavinbunney/kubectlprovider同样内置了旧版Kubernetes客户端逻辑,无法兼容新的认证API版本要求。
可行修复方案
- 升级Terraform依赖版本(推荐长期方案)
将AWS provider升级至4.x及以上版本,EKS模块升级至18.x及以上版本,若仍需使用kubectl provider则同步升级至最新兼容版本。新版依赖生成的kubeconfig会默认使用受支持的client.authentication.k8s.io/v1beta1及以上认证API版本,可直接适配新版客户端。升级操作前务必先执行terraform plan确认资源变更范围,避免误修改现有集群配置。 - 临时替换kubeconfig认证版本(快速修复方案)
若暂时不想调整Terraform模块版本,可在CI流水线生成kubeconfig的步骤后,添加命令直接替换配置中的旧API版本,1.21版本EKS完全兼容v1beta1认证API,替换后即可正常连接集群:sed -i 's/client.authentication.k8s.io\/v1alpha1/client.authentication.k8s.io\/v1beta1/g' ~/.kube/config - 锁定CI环境客户端版本(不推荐)
可将Gitlab CI Runner内的kubectl、Helm、AWS CLI版本锁定至仍支持v1alpha1 API的旧版本(如kubectl<=1.23、AWS CLI<=1.23),即可临时恢复流水线运行。但该方案存在安全隐患,后续EKS版本升级会彻底移除旧认证API支持,维护成本较高。
内容的提问来源于stack exchange,提问作者CuriousMind
相关产品推荐
相关产品推荐

