k8s 集群证书过期:Unable to connect to the server: x509: certificate has expired or is not yet valid

内容纲要

概述

如果你的k8s集群运行超过一年,那么你可能会遇到以下这样问题:


Unable to connect to the server: x509: certificate has expired or is not yet valid

上面的报错可能是因为你使用kubectl命令对k8s资源进行CURD时报错的,比如:


kubectl get nodes

Unable to connect to the server: x509: certificate has expired or is not yet valid

背景

公司使用阿里云ECS自建了k8s集群,k8s版本为1.23.8。在之前某个日子里使用跳板机连接k8s master使用kubectl命令查看node时突然报了证书错误。

分析

在看到这个问题之后,我们就开启了搜索之路,于是就看到了:
k8s官网文档中明确指出,如果客户端证书是通过kubeadm生成的,那么这些证书的有效期为1年,也就是一年后会过期。
我们k8s集群并没有使用自定义的证书,使用kubeadm生成的所有就有了这个问题。

解决

证书过期查看

首先,根据搜索到结果,我们首先查看哪些证书过期:

kubeadm certs check-expiration

更新证书


kubeadm certs renew all
[renew] Reading configuration from the cluster...
[renew] FYI: You can look at this config file with 'kubectl -n kube-system get cm kubeadm-config -o yaml'
[renew] Error reading configuration from the Cluster. Falling back to default configuration

certificate embedded in the kubeconfig file for the admin to use and for kubeadm itself renewed
certificate for serving the Kubernetes API renewed
certificate the apiserver uses to access etcd renewed
certificate for the API server to connect to kubelet renewed
certificate embedded in the kubeconfig file for the controller manager to use renewed
certificate for liveness probes to healthcheck etcd renewed
certificate for etcd nodes to communicate with each other renewed
certificate for serving etcd renewed
certificate for the front proxy client renewed
certificate embedded in the kubeconfig file for the scheduler manager to use renewed

Done renewing certificates. You must restart the kube-apiserver, kube-controller-manager, kube-scheduler and etcd, so that they can use the new certificates.

重启kubelet等相关组件

其次重启kubelet(如果你的kube-apiserver, controller-manager, scheduler等k8s组件是容器形式运行的,那么你还得重启它们。)

sudo systemctl restart kubelet

更新kubeconfig文件

最后,想要使用kubectl命令行的话,还得更新kubeconfig:
使用以下命令重新生成kubeconfig文件:

sudo kubeadm init phase kubeconfig admin

然后重新将文件复制到用户目录下:

mkdir -p $HOME/.kube
sudo cp /etc/kubernetes/admin.conf $HOME/.kube/config
sudo chown $(id -u):$(id -g) $HOME/.kube/config

其他方案

  1. 在k8s集群初始化时指定证书目录,使用自定义的证书
  2. External CA模式

疑惑

k8s集群中的证书是干什么的?

证书就是用来提高安全性的嘛。
k8s需要使用公钥基础设施(PKI)来进行基于TLS的身份验证。如果你使用kubeadm安装k8s,集群中的证书会自动生成。你也可以自己生成证书。

有哪些证书?

Kubernetes 需要 PKI 证书来执行以下操作:

  • 客户端证书:用于 kubelet 认证到 API 服务器
  • Kubelet 服务器证书:用于 API 服务器与 kubelet 之间的通信
  • API 服务器端证书:用于 API 服务器端点的安全通信
  • 管理员客户端证书:用于集群管理员认证到 API 服务器
  • API 服务器客户端证书:用于 API 服务器与 kubelet 之间的通信
  • API 服务器客户端证书:用于 API 服务器与 etcd 之间的通信
  • 控制器管理器客户端证书/kubeconfig:用于控制器管理器与 API 服务器之间的通信
  • 调度器客户端证书/kubeconfig:用于调度器与 API 服务器之间的通信
  • 前端代理客户端和服务器证书:用于前端代理的客户端和服务器通信

存储到哪里?

默认:/etc/kubernetes/pki, 这儿找不到则:/etc/kubernetes

参考

  1. Certificate Management with kubeadm
  2. PKI certificates and requirements

发表评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注

滚动至顶部