在kubernetes中1.28以前的版本如果想升级几年不太支持,但是每次要手动进行续签又太麻烦,所以我想做一个定时续签的功能,这样保证每次到期的时候不需要认为的去操作,
[wolf💀wulaoer.org 🔥🔥🔥🔥 ~ ]$vim /usr/local/bin/k8s-renew-certs.sh #!/bin/bash CERT_DIR=/etc/kubernetes/pki K8S_DIR=/etc/kubernetes RENEW_THRESHOLD_DAYS=30 TODAY=$(date +%F) LOG=/var/log/k8s-cert-renew-$TODAY.log echo "[$(date)] ====== 证书检查开始 ======" >> $LOG # --------------------- # 检查证书剩余天数 # --------------------- check_cert() { local cert=$1 local end_date=$(openssl x509 -in $cert -noout -enddate | cut -d= -f2) local end_timestamp=$(date -d "$end_date" +%s) local now=$(date +%s) local diff_days=$(( (end_timestamp - now) / 86400 )) echo "[$(date)] 证书: $cert 剩余 $diff_days 天" >> $LOG if (( diff_days < RENEW_THRESHOLD_DAYS )); then return 0 else return 1 fi } need_renew=false for cert in $CERT_DIR/*.crt; do if check_cert $cert; then need_renew=true fi done # --------------------- # 执行证书续签(仅当需要时) # --------------------- if [ "$need_renew" = true ]; then echo "[$(date)] 触发证书续签: kubeadm certs renew all" >> $LOG kubeadm certs renew all >> $LOG 2>&1 echo "[$(date)] 证书续签完成。" >> $LOG # --------------------- # 更新 kubeconfig # --------------------- echo "[$(date)] 更新 kubeconfig..." >> $LOG cp -f $K8S_DIR/admin.conf /root/.kube/config cp -f $K8S_DIR/admin.conf $K8S_DIR/controller-manager.conf cp -f $K8S_DIR/admin.conf $K8S_DIR/scheduler.conf echo "[$(date)] kubeconfig 更新完成。" >> $LOG # --------------------- # 重启 kubelet # --------------------- echo "[$(date)] 重启 kubelet..." >> $LOG systemctl restart kubelet echo "[$(date)] kubelet 已重启。" >> $LOG else echo "[$(date)] 无证书接近到期,不执行续签。" >> $LOG fi # --------------------- # 清理超过 7 天的日志(安全) # --------------------- echo "[$(date)] 清理 7 天前日志..." >> $LOG find /var/log/ -name "k8s-cert-renew-*.log" -mtime +7 -exec rm -f {} \; echo "[$(date)] ====== 证书检查结束 ======" >> $LOG
我这里的流程是先检查证书剩余天数,然后根据剩余天数进行,如果剩余天数小于30天就自动续签,并且重启kubelet,如果不到就不续签,然后打印日志,并且只保留7天的日志内容.这个脚本是做好了,我们需要他想服务一样每天进行检查,所以要做一个定时器
[wolf💀wulaoer.org 🔥🔥🔥🔥 ~ ]$ chmod +x /usr/local/bin/k8s-renew-certs.sh [wolf💀wulaoer.org 🔥🔥🔥🔥 ~ ]$ vim /etc/systemd/system/k8s-cert-renew.service [Unit] Description=Kubernetes Auto Renew Certificates [Service] Type=oneshot ExecStart=/usr/local/bin/k8s-renew-certs.sh [wolf💀wulaoer.org 🔥🔥🔥🔥 ~ ]$ vim /etc/systemd/system/k8s-cert-renew.timer [Unit] Description=Run Kubernetes Cert Renew Daily [Timer] OnCalendar=*-*-* 03:00 Persistent=true [Install] WantedBy=multi-user.target
每天早上3点执行定时器,检查证书脚本,然后让这个定时器开机自启动
[wolf💀wulaoer.org 🔥🔥🔥🔥 ~ ]$ systemctl daemon-reload [wolf💀wulaoer.org 🔥🔥🔥🔥 ~ ]$ systemctl enable --now k8s-cert-renew.timer
这样后期就不需要在意什么时候到期什么时候过期了,因为我需要在当前节点上执行集群命令,所以我要更新当前节点的配置文件,这样不需要手动修改了.

您可以选择一种方式赞助本站
支付宝扫一扫赞助
微信钱包扫描赞助
赏