Important

- SSL certificates used for secure communication between nodes in the Kubernetes cluster are self-signed and have a default validity period of 1 year.

- It is critical to renew these certificates before they expire. However, automating this renewal process is generally not recommended. Kubernetes typically encourages performing certificate renewal in conjunction with upgrades to new versions. This approach ensures that the system remains up to date in terms of both security and compatibility.

- Therefore, we strongly recommend that the certificate renewal process be carried out in a planned and controlled manner to minimize and control potential risks. This is the best method to prevent possible interruptions and ensure security.


vi k8s-certs-check.sh
CODE
#!/bin/bash
 
# Threshold number of days
THRESHOLD_DAYS=35
NEED_RENEWAL=false 
LOG_FILE="$(dirname "$0")/cert_renewal.log"
current_date=$(date '+%Y-%m-%d %H:%M:%S')
 
sudo kubeadm certs check-expiration > /tmp/cert_check.txt
 
# Find the 'CERTIFICATE' header to extract the first row of data
first_data_line=$(grep -A 100 'CERTIFICATE' /tmp/cert_check.txt | tail -n +2 | head -n 1)
 
# Extract number of days
days=$(echo "$first_data_line" | awk '{print $(NF-2)}' | grep -Eo '[0-9]+')
 
echo "Number of days: $days"
 
# Check if the number of days is less than the threshold
if [[ -n "$days" && "$days" -lt "$THRESHOLD_DAYS" ]]; then
    echo "Certificate expiration is less than $THRESHOLD_DAYS days: $first_data_line"
    NEED_RENEWAL=true
fi
 
if [[ -n "$days" && "$days" -lt "$THRESHOLD_DAYS" ]]; then
    echo "[$current_date] The certificate is almost expired. Renewal process is starting..." | tee -a "$LOG_FILE"
    sudo kubeadm certs renew all
 
    sudo systemctl restart kubelet
 
    echo -e "\033[0;32m[$current_date] Renewal process completed! Certificates expiration is being checked again...\033[0m" | tee -a "$LOG_FILE"
    sudo kubeadm certs check-expiration | tee -a "$LOG_FILE"
else
    echo -e "\033[0;32m[$current_date] Certificates have sufficient duration, no need for renewal.\033[0m" | tee -a "$LOG_FILE"
fi
CODE


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

It adds the cert_renewal.log file to the directory where you run the script and you can watch the execution logs from there.


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 * * /path/k8s-certs-check.sh
CODE

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