vi k8s-certs-check.sh
CODE
#!/bin/bash
 
set -e
 
renewed=0
 
configfiles=(
    /etc/kubernetes/kubelet.conf
    /etc/kubernetes/admin.conf
    /etc/kubernetes/scheduler.conf
    /etc/kubernetes/controller-manager.conf
)
 
certfiles=(
    /etc/kubernetes/pki/apiserver.crt
    /etc/kubernetes/pki/apiserver-etcd-client.crt
    /etc/kubernetes/pki/apiserver-kubelet-client.crt
    /etc/kubernetes/pki/ca.crt
    /etc/kubernetes/pki/front-proxy-ca.crt
    /etc/kubernetes/pki/front-proxy-client.crt
    /etc/kubernetes/pki/etcd/ca.crt
    /etc/kubernetes/pki/etcd/client.crt
    /etc/kubernetes/pki/etcd/peer.crt
    /etc/kubernetes/pki/etcd/server.crt
)
 
get_expire_time() {
    date=$(echo "$1" | openssl x509 -enddate -noout | sed "s/.*=\(.*\)/\1/")
    date_s=$(date -d "${date}" +%s)
    now_s=$(date -d now +%s)
    date_diff=$(( (date_s - now_s) / 86400 ))
    if [ $date_diff -eq 0 ]; then
        expires="$(( (date_s - now_s) / 3600 )) hours"
    else
        expires="$date_diff days"
    fi
 
    echo "$expires"
}
 
renew_certificate() {
    sudo kubeadm certs renew all
    renewed=1
}
 
for configfile in ${configfiles[@]}; do
    if [ ! -f $configfile ]; then
        continue
    fi
 
    echo -n "Config file $configfile: "
 
    CERT_DATA=$(cat $configfile | grep client-certificate-data | sed 's/    client-certificate-data: //')
    CERT_FILE=$(cat $configfile | grep client-certificate | sed 's/    client-certificate: //')
    if [ "$CERT_DATA" ]; then
        expires=$(get_expire_time "$(echo $CERT_DATA | base64 -d)")
    elif [ "$CERT_FILE" ]; then
        expires=$(get_expire_time "$(cat $CERT_FILE)")
    else
        echo "no client certificate found"
        continue
    fi
 
    echo "certificate expires in $expires"
 
    # If the certificate expires less than 30 days, renewal is performed.
     if [ ${expires%% *} -lt 30 ]; then
        renew_certificate "$CERT_FILE"
    fi
done
 
for certfile in ${certfiles[@]}; do
    if [ ! -f $certfile ]; then
        continue
    fi
 
    echo -n "Certificate $certfile: "
    expires=$(get_expire_time "$(cat $certfile)")
    echo "certificate expires in $expires"
 
    
	 #If the certificate expires less than 30 days, renewal is performed.
     if [ ${expires%% *} -lt 30 ]; then
        renew_certificate "$certfile"
    fi
done
echo
 
if [ $renewed -eq 1 ]; then
    echo -e "\e[32mCertificates renewed successfully.\e[0m"
    echo "You can see your new certificate durations by running the code again."
else
    echo -e "\e[31mThe certificate period is still valid.\e[0m"
fi
CODE


sudo chmod +x k8s-certs-check.sh
./k8s-certs-check.sh
CODE


If you wish, you can ensure that the script runs at a specific time or during a time period. For this, cron can be used.

sudo crontab -e 
CODE

Add the following line into the opened file.

59 23 1 * * /File_Path/k8s-certs-check.sh >> /var/log/k8s-cert-check.log 2>&1
CODE

In the example usage, the script will run at 11:59 PM on the 1st day of every month.