距离上一次更新该文章已经过了 550 天,文章所描述的內容可能已经发生变化,请留意。
前言
官方文档
K3s 启动时会自动生成 CA 证书,CA 证书的有效期为 10 年。其他证书有效期为 1 年,如果证书已经过期或剩余的时间不足 90 天,则在 K3s 重启时轮换证书。K3s 服务只是一个进程,K3s 服务重启不会影响正在运行的 pod,也不会影响你的业务。
证书轮换方式(3种任选其一)
使用crontab + shell脚本
方式实现证书轮换
编写脚本 - upgradeCert.sh,并放在主节点服务器上
查看主节点位置:kubectl get nodes -l 'node-role.kubernetes.io/control-plane'|awk '{if (NR>1){print $1}}'
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| #!/bin/bash
DIR="/var/lib/rancher/k3s/server/tls" now=$(date +%s)
for FILE in $(find $DIR -maxdepth 1 -type f -name "*.crt"); do tempCertEndDate=$(openssl x509 -noout -in $FILE -enddate) certEndDate=$(echo "$tempCertEndDate" |cut -d"=" -f2) tempFormatEndDate=$(date -u -d "$certEndDate" +'%Y-%m-%d %H:%M:%S') formatEndDate=$(date +%s -d "$tempFormatEndDate") restartDate=$(date +"%Y-%m-%d %H:%M:%S") days=$((($formatEndDate - $now)/86400)) if [ $days -lt 90 ]; then mkdir -p /var/log/k3s systemctl restart k3s echo -e $restartDate" - 证书即将过期,重启k3s服务,剩余天数:"$days >> /var/log/k3s/restart_k3s.log break fi done
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| #!/bin/bash
DIR="/var/lib/rancher/k3s/agent" now=$(date +%s)
for FILE in $(find $DIR -maxdepth 1 -type f -name "*.crt"); do tempCertEndDate=$(openssl x509 -noout -in $FILE -enddate) certEndDate=$(echo "$tempCertEndDate" |cut -d"=" -f2) tempFormatEndDate=$(date -u -d "$certEndDate" +'%Y-%m-%d %H:%M:%S') formatEndDate=$(date +%s -d "$tempFormatEndDate") restartDate=$(date +"%Y-%m-%d %H:%M:%S") days=$((($formatEndDate - $now)/86400)) if [ $days -lt 90 ]; then mkdir -p /var/log/k3s systemctl restart k3s-agent echo -e $restartDate" - 证书即将过期,重启k3s服务,剩余天数:"$days >> /var/log/k3s/restart_k3s.log break fi done
|
1 2 3 4 5 6
| SHELL=/bin/bash PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin MAILO=root */5 * * * * flock -xn /tmp/stargate.lock -c '/usr/local/qcloud/stargate/admin/start.sh > /dev/null 2>&1 &'
0 02 * * Mon sh ~/upgradeCert.sh
|
K3s 已经加入手动轮换证书的功能,这样就可以更新现有证书的过期时间来延长证书有效期。
服务器证书自颁发日起 365 天内有效。每次启动 K3s 时,已过期或 90 天内过期的证书都会自动更新。
- 要手动轮换服务器证书,请使用
k3s certificate rotate
子命令:
1 2 3 4 5 6 7 8 9 10
|
systemctl stop k3s
k3s certificate rotate
systemctl start k3s
systemctl restart k3s-agent
|
1
| k3s certificate rotate --service <SERVICE>,<SERVICE>
|
可以轮换的证书:admin
、api-server
、controller-manager
、scheduler
、k3s-controller
, k3s-server
, cloud-controller
, etcd
, auth-proxy
, kubelet
,kube-proxy
。
周期执行一次重启
例如每几个月执行一次重启
但是最好保证agent在server之后执行重启操作,以保证agent获取到的是最新的证书
1 2 3 4 5 6 7 8
| SHELL=/bin/bash PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin MAILO=root */5 * * * * flock -xn /tmp/stargate.lock -c '/usr/local/qcloud/stargate/admin/start.sh > /dev/null 2>&1 &'
30 2 1 * * systemctl restart k3s
|
关于 k3s agent 证书轮换
k3s-agent下存在着一个文件夹/var/lib/rancher/k3s/agent
,下面会包含一些证书,例如:/var/lib/rancher/k3s/agent/client-k3s-controller.crt
这个证书,它是k3s-agent用于与k3s-server通信的客户端证书,这类证书通常会在k3s-agent启动时生成,并具有过期时间。默认情况下,这个证书的有效期为一年,过期后需要更新。
详见 discus