Skip to content

Instantly share code, notes, and snippets.

@CJCShadowsan
Last active January 10, 2025 13:13
Show Gist options
  • Select an option

  • Save CJCShadowsan/3de1e5f25b5cbb463cc12579319e9d1c to your computer and use it in GitHub Desktop.

Select an option

Save CJCShadowsan/3de1e5f25b5cbb463cc12579319e9d1c to your computer and use it in GitHub Desktop.
apiVersion: batch/v1
kind: CronJob
metadata:
name: check-cert-expiry
namespace: default
spec:
schedule: "0 2 * * *" # Runs daily at 2:00 AM
jobTemplate:
spec:
template:
spec:
serviceAccountName: cert-manager-sa
containers:
- name: cert-expiry-checker
image: registry.k8s.io/kubectl:latest
imagePullPolicy: IfNotPresent
command:
- /bin/bash
- -c
- |
set -e
echo "Checking for certificates expiring within 15 days..."
# Get all certificates in JSON format
certificates=$(kubectl get certificates --all-namespaces -o json)
# Parse JSON and find certificates expiring within 15 days
expiring_certs=$(echo "$certificates" | jq -r '.items[] | select((.status.notAfter | fromdateiso8601) < (now + 15 * 86400)) | [.metadata.namespace, .metadata.name] | @csv')
if [[ -z "$expiring_certs" ]]; then
echo "No certificates expiring within 15 days."
else
echo "Found expiring certificates. Deleting them to trigger renewal:"
echo "$expiring_certs"
# Loop through each certificate and delete it
while IFS=',' read -r namespace name; do
echo "Deleting certificate $name in namespace $namespace..."
kubectl delete certificate "$name" -n "$namespace"
done <<< "$expiring_certs"
echo "Certificate renewal triggered."
fi
env:
- name: KUBECONFIG
value: /root/.kube/config
volumeMounts:
- name: kubeconfig
mountPath: /root/.kube
readOnly: true
restartPolicy: OnFailure
volumes:
- name: kubeconfig
secret:
secretName: kubeconfig-secret
---
apiVersion: v1
kind: Secret
metadata:
name: kubeconfig-secret
namespace: default
stringData:
config: |
# Add your kubeconfig file content here
apiVersion: v1
kind: Config
clusters:
- cluster:
certificate-authority-data: REDACTED
server: https://<KUBERNETES_SERVER>
name: kubernetes
contexts:
- context:
cluster: kubernetes
user: kubernetes-admin
name: kubernetes-admin@kubernetes
current-context: kubernetes-admin@kubernetes
users:
- name: kubernetes-admin
user:
token: REDACTED
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment