Created
March 4, 2020 12:14
-
-
Save jstangroome/b708724c51f9c769c3a8693ee54092f3 to your computer and use it in GitHub Desktop.
kubectl evict in bash
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 | |
print_usage () { | |
printf 'Usage: kubectl evict -n <namespace> <pod>\n' >&2 | |
} | |
main () { | |
if [ "-n" != "$1" ] && [ "--namespace" != "$1" ] | |
then | |
print_usage | |
return 1 | |
fi | |
shift | |
# TODO handle arbitrary argument order | |
local ns=$1 pod=$2 | |
if [ -z "${ns}" ] && [ -z "${pod}" ] | |
then | |
print_usage | |
return 1 | |
fi | |
local body sock_dir kubectl_proxy_pid curl_exit counter | |
printf -v body '{"apiVersion":"policy/v1beta1","kind":"Eviction","metadata":{"namespace":"%s","name":"%s"}}' \ | |
"${ns}" "${pod}" | |
sock_dir=$(mktemp -d) | |
kubectl proxy -u "${sock_dir}/kube.sock" >/dev/null & | |
kubectl_proxy_pid=$! | |
sleep 1 | |
counter=15 | |
while [ ! -e "${sock_dir}/kube.sock" ] && [ 0 -lt "${counter}" ] | |
do | |
sleep 0.1 | |
counter=$((counter - 1)) | |
done | |
if ! kill -n 0 "${kubectl_proxy_pid}" | |
then | |
wait "${kubectl_proxy_pid}" | |
return | |
fi | |
curl --unix-socket "${sock_dir}/kube.sock" \ | |
-d "${body}" \ | |
-H 'Content-Type: application/json' \ | |
-s -o /dev/null -w '%{http_code}\n' \ | |
"http://localhost/api/v1/namespaces/${ns}/pods/${pod}/eviction" | |
#TODO curl --retry to honour 429's retry-header response (assuming v7.66+) | |
curl_exit=$? | |
kill "${kubectl_proxy_pid}" | |
wait "${kubectl_proxy_pid}" 2>/dev/null | |
rm -f "${sock_dir}/kube.sock" | |
rm -d "${sock_dir}" | |
return "${curl_exit}" | |
} | |
main "$@" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment