Jenkins中执行kubectl命令失败但终端运行正常的问题排查
问题描述
Jenkins部署在已连接AKS和ACR的跳板机上,终端执行kubectl命令正常,但在Jenkins流水线中执行时失败。
Jenkins流水线脚本
stage('Deploy Image') { steps { echo 'Deploying Image to AKS ....' withKubeConfig(caCertificate: '', clusterName: '', contextName: '', credentialsId: '', namespace: 'icx-preprod', restrictKubeConfigAccess: false, serverUrl: '') // sh 'kubectl delete statetfulset dpms -n icx-preprod' sh 'kubectl apply -f /home/icx-user/nonwebpa-yamls/rt/rt.yaml -n preprod' } }
报错信息
错误1
+ kubectl apply -f /home/icx-user/nonwebpa-yamls/rt/rt.yaml -n preprod Error from server (NotFound): the server could not find the requested resource
错误2
+ kubectl get pods -n preprod E1010 07:30:08.881057 47786 memcache.go:265] couldn't get current server API group list: invalid character '<' looking for beginning of value E1010 07:30:08.897305 47786 memcache.go:265] couldn't get current server API group list: invalid character '<' looking for beginning of value E1010 07:30:08.910836 47786 memcache.go:265] couldn't get current server API group list: invalid character '<' looking for beginning of value E1010 07:30:08.931700 47786 memcache.go:265] couldn't get current server API group list: invalid character '<' looking for beginning of value E1010 07:30:08.950612 47786 memcache.go:265] couldn't get current server API group list: invalid character '<' looking for beginning of value error: invalid character '<' looking for beginning of value [Pipeline] } [kubernetes-cli] kubectl configuration cleaned up
解决步骤
修正
withKubeConfig配置
当前withKubeConfig的所有参数为空,会覆盖Jenkins执行环境的kubeconfig,导致kubectl无法正确连接AKS。要么直接移除这个块,让kubectl使用默认配置;要么填充正确的clusterName、contextName、credentialsId、serverUrl等参数(可从跳板机~/.kube/config中提取)。统一Jenkins用户与终端用户的kubeconfig
Jenkins默认以jenkins用户运行,和你终端使用的icx-user不是同一个用户,kubeconfig路径不同。可以:- 复制
/home/icx-user/.kube/config到/var/lib/jenkins/.kube/config,并修改文件权限为jenkins用户可读; - 或者在流水线中直接指定kubeconfig路径:
sh 'export KUBECONFIG=/home/icx-user/.kube/config && kubectl apply -f /home/icx-user/nonwebpa-yamls/rt/rt.yaml -n preprod'
- 复制
排查资源与命名空间问题
第一个NotFound错误可能是:- 命名空间
preprod不存在,先执行kubectl create namespace preprod; - YAML文件中的资源定义有误,或者对应API组未在AKS集群启用。
- 命名空间
解决
invalid character '<'错误
这个错误是因为kubectl收到了HTML响应(比如代理登录页、错误页),处理方式:- 检查Jenkins的全局代理设置,确保AKS API服务器地址加入不使用代理的列表;
- 确认AKS API服务器地址是正确的HTTPS地址,没有被错误配置为HTTP。
内容的提问来源于stack exchange,提问作者RadiumBall
相关产品推荐
相关产品推荐

