Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
cleanup offline nodes (jenkins / ecs)
#!/usr/bin/env bash
throw_exception() {
echo "Ooops!"
echo 'Stack trace:' 1>&2
while caller $((n++)) 1>&2; do :; done;
exit 1
}
set -E
trap 'throw_exception' ERR
jenkins::computer_is_offline() {
if [[ "$(echo "${1}" | jq -j '.offline')" == "true" ]]; then
return 0
fi
return 1
}
jenkins::computer_delete() {
local buf
local crumb
buf="$(curl \
--retry 3 \
--fail \
--show-error \
--silent \
--user "${JENKINS_AUTH}" \
"${JENKINS_URL}computer/${1}/delete")"
if [[ "${buf}" =~ crumb.init\(\"Jenkins-Crumb\",\ \"([^\"]+)\"\)\; ]]; then
crumb="${BASH_REMATCH[1]}"
else
return 1
fi
curl \
--retry 3 \
--fail \
--show-error \
--silent \
--user "${JENKINS_AUTH}" \
-d "Jenkins-Crumb=${crumb}" \
-d 'Submit=yes' \
"${JENKINS_URL}computer/${1}/doDelete"
}
required_vars=( \
JENKINS_URL \
JENKINS_AUTH \
)
for required_var in "${required_vars[@]}"; do
if [[ -z "${!required_var}" ]]; then
echo "required var missing (${required_var})" 1>&2
exit 2
fi
done
computers=( $(curl \
--retry 3 \
--fail \
--show-error \
--silent \
--user "${JENKINS_AUTH}" \
"${JENKINS_URL}computer/api/json" | jq -r '.computer[] | @base64') )
for computer in "${computers[@]}"; do
computer="$(_jq "${computer}")"
computer_name="$(echo "${computer}" | jq -j '.displayName')"
if [[ "${computer_name}" == "master" ]]; then
continue
fi
if jenkins::computer_is_offline "${computer}" && [[ "$(echo "${computer}" | jq -j '.offlineCauseReason')" == "Time out for last 5 try" ]]; then
echo "deleting offline computer: ${computer_name}"
jenkins::computer_delete "${computer_name}"
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment