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.
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.