Skip to content

Commit

Permalink
add script
Browse files Browse the repository at this point in the history
  • Loading branch information
badra001 committed Dec 7, 2022
1 parent d7d0e72 commit e519288
Showing 1 changed file with 78 additions and 0 deletions.
78 changes: 78 additions & 0 deletions examples/certificate/refresh-certs.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
#!/usr/bin/env bash

# Provide an error message and usage instructions.
usage () {
local msg="${1}"; shift

cat >&2 <<EOF
$msg:
$0 issuerName
issuerName - The name of the issuer that has been updated for which every
related certificate needs to be reissued.
EOF
exit 1
}

# Recreate a certificate and restart the pods that make use of said cert.
#
# Deletes the secret and then waits until cert-manager reissues a new secret.
# Once the new secret exists, all of the pods, one at a time, that make use of
# that certificate are deleted. Between each pod being restarted, wait for
# the previously deleted pod to be in ready state before deleting the next.
#
# $1 - The name of the secret created by the certificate request
# $2 - The namespace in which the certificate / secret exists.
refresh_cert() {
local name="${1}"; shift
local namespace="${1}"; shift
local pods pod_status
pods="{range .items[*]}"
pods+={@.metadata.name}
pods+="{range @.spec.volumes[?(@.secret.secretName==\"$name\")]}"
pods+={@.secret.secretName}
pods+="{end}"
pods+="{\"\n\"}"
pods+="{end}"
pod_status="{.status.conditions[?(@.type=='Ready')].status}"

kubectl -n "$namespace" delete secret "$name"
while ! kubectl -n "$namespace" get secret "$name"; do
sleep 10
done
kubectl -n "$namespace" get pods -o jsonpath="$pods" | \
grep "$name" | awk '{print $1}' | \
while read -r pod; do
kubectl -n "$namespace" delete pod "$pod"
while [[ "$(kubectl -n "$namespace" get pod "$pod" \
-o jsonpath="$pod_status")" != "True" ]]; do
sleep 10
done
done
}

# Recreate the secrets associated with certificates created by an issuer
#
# $1 - The name of the issuer that was used to create the certificate.
refresh_certs() {
local issuer="${1}"; shift
local jsonpath name namespace
jsonpath="{range .items[?(@.spec.issuerRef.name==\"$issuer\")]}"
jsonpath+="{.spec.secretName}{\" \"}{.metadata.namespace}{\"\n\"}"
jsonpath+="{end}"

if [[ $issuer == "" ]]; then
usage "Issuer name not specified"
fi

kubectl get cert --all-namespaces -o jsonpath="$jsonpath" | \
while read -r cert_details; do
name="${cert_details%' '*}"
namespace="${cert_details#*' '}"
echo "name: $name; namespace: $namespace"
refresh_cert "$name" "$namespace"
done
}

return 0 > /dev/null 2>&1 || refresh_certs "$@"

0 comments on commit e519288

Please sign in to comment.