- SSL certificates used for secure communication between nodes in Kubernetes cluster are self-signed and have a 1 year validity period by default.
- It is critical to renew these certificates before they expire. However, automating this renewal process is generally not recommended. Kubernetes generally encourages doing certificate renewal operations together with upgrades to new versions. This approach ensures the system stays current both in terms of security and compatibility.
- Therefore, we strongly recommend that the certificate renewal process be executed in a planned and controlled manner to minimize potential risks and keep it under control. This is the best method to prevent possible interruptions and ensure security.
Creating Script
Create the script file:
Script content:
#!/bin/bash
# Threshold 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
# Extract first data line by finding 'CERTIFICATE' header
first_data_line=$(grep -A 100 'CERTIFICATE' /tmp/cert_check.txt | tail -n +2 | head -n 1)
# Extract day count
days=$(echo "$first_data_line" | awk '{print $(NF-2)}' | grep -Eo '[0-9]+')
echo "Day count: $days"
# Check if day count is less than 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] Certificate expiration is low. Starting renewal process..." | tee -a "$LOG_FILE"
sudo kubeadm certs renew all
sudo systemctl restart kubelet
echo -e "\033[0;32m[$current_date] Renewal process completed! Certificate 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] Certificate expiration is sufficient, no renewal needed.\033[0m" | tee -a "$LOG_FILE"
fi
Making Script Executable
sudo chmod +x k8s-certs-check.sh
./k8s-certs-check.sh
The script adds a cert_renewal.log file to the directory where you run it, and you can monitor execution logs from here.
Scheduled Execution (Cron)
You can ensure the script runs at a specific time or time period if desired. Cron can be used for this:
Add the following line to the opened file:
59 23 1 * * /path/k8s-certs-check.sh
In the example usage, the script will run on the 1st day of each month at 23:59.