Skip to content

Instantly share code, notes, and snippets.

@taxilian
Created September 24, 2024 20:39
Show Gist options
  • Save taxilian/867546b43e1f2515a5a77a0a86a5bc89 to your computer and use it in GitHub Desktop.
Save taxilian/867546b43e1f2515a5a77a0a86a5bc89 to your computer and use it in GitHub Desktop.
Bash script to check the certificate expirations in your kubeconfig file
#!/bin/bash
# Function to extract and decode certificate
extract_cert() {
echo "$1" | base64 -d 2>/dev/null | openssl x509 -noout -enddate 2>/dev/null | cut -d= -f2
}
# Function to calculate days until expiry
days_until_expiry() {
local expiry_date="$1"
local current_date=$(date -u +"%b %d %H:%M:%S %Y GMT")
local expiry_seconds=$(date -j -f "%b %d %H:%M:%S %Y GMT" "$expiry_date" "+%s")
local current_seconds=$(date -j -f "%b %d %H:%M:%S %Y GMT" "$current_date" "+%s")
echo $(( (expiry_seconds - current_seconds) / 86400 ))
}
# Extract all user data including names and certificate data
user_data=$(kubectl config view --raw -o json | jq -c '.users[]')
# Check each user's certificate
echo "$user_data" | while read -r user; do
name=$(echo "$user" | jq -r '.name')
cert=$(echo "$user" | jq -r '.user."client-certificate-data"')
if [ "$cert" != "null" ] && [ -n "$cert" ]; then
expiry_date=$(extract_cert "$cert")
if [ -n "$expiry_date" ]; then
days_left=$(days_until_expiry "$expiry_date")
echo "User: $name"
echo "Certificate expires on: $expiry_date"
echo "Days until expiry: $days_left"
echo "---"
else
echo "User: $name"
echo "Failed to extract expiry date from certificate."
echo "---"
fi
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment