Created
December 22, 2021 12:59
-
-
Save carlosrodlop/a22f147d09d6fb954faa857c8a04cd9b to your computer and use it in GitHub Desktop.
Bash script to move Jenkins apps to "quietmode" for a specific time passed as parameter before draining node of your CI k8s cluster
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
set -euo pipefail | |
shopt -s inherit_errexit nullglob compat"${BASH_COMPAT=42}" | |
#Parameters | |
JENKINS_USER_ID=example.user | |
JENKINS_API_TOKEN=****** | |
JENKINS_NS_LIST=("ns-example-1" "ns-example-2") | |
SLEEP_SEC=3600 | |
quietDownJenkinsApps(){ | |
for ns in "${JENKINS_NS_LIST[@]}"; do | |
mapfile -t podsPerNsList < <(kubectl get pods -n "$ns" | awk '{print $1}' | sed "1d") | |
if [ ${#podsPerNsList[@]} -gt 0 ]; then | |
for pod in "${podsPerNsList[@]}"; do | |
isJenkinsApp=$(kubectl exec "$pod" -n "$ns" -- sh -c "[ -d /var/jenkins_home ] && echo \"true\" || echo \"false\"" ) | |
if [ "$isJenkinsApp" = "true" ]; then | |
jenkinsUrl=$(kubectl exec "$pod" -n "$ns" -- cat /var/jenkins_home/jenkins.model.JenkinsLocationConfiguration.xml | grep "<jenkinsUrl>" | sed -n 's:.*<jenkinsUrl>\(.*\)</jenkinsUrl>.*:\1:p') | |
# https://support.cloudbees.com/hc/en-us/articles/216118748 | |
action="quietDown" | |
response=$(curl --write-out "%{http_code}\n" --user "${JENKINS_USER_ID}:${JENKINS_API_TOKEN}" -XPOST "${jenkinsUrl}/${action}" --silent) | |
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Status | |
if [ "$response" -lt "400" ]; then | |
echo "[INFO] Moving $jenkinsUrl to $action ..." | |
fi | |
fi | |
done | |
fi | |
done | |
} | |
siestaTime(){ | |
echo "[INFO] Enter in siesta mode for $SLEEP_SEC sec..." | |
sleep $SLEEP_SEC | |
} | |
drainNodes(){ | |
mapfile -t allNodesList < <(kubectl get nodes | awk '{print $1}' | sed "1d") | |
if [ ${#allNodesList[@]} -gt 0 ]; then | |
for node in "${allNodesList[@]}"; do | |
kubectl drain "$node" --ignore-daemonsets --delete-emptydir-data | |
done | |
fi | |
} | |
quietDownJenkinsApps | |
siestaTime | |
drainNodes |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment