Skip to content

Instantly share code, notes, and snippets.

@eshleebien
Created July 19, 2019 08:34
Show Gist options
  • Select an option

  • Save eshleebien/7214a2e0afe4f0698ba31e5009392b5b to your computer and use it in GitHub Desktop.

Select an option

Save eshleebien/7214a2e0afe4f0698ba31e5009392b5b to your computer and use it in GitHub Desktop.
kubectl drain using kubernetes api
HOSTNAME=`curl -s http://169.254.169.254/latest/meta-data/local-hostname`
SERVER=$1
TOKEN=$2
curl -s --insecure -k -v -H "Accept: application/json" -H "Authorization: Bearer $TOKEN" -XPATCH -d '{"spec":{"unschedulable":true}}' -H "Content-Type: application/merge-patch+json" $SERVER/api/v1/nodes/$HOSTNAME
for each in $(curl -s -k -H "Authorization: Bearer $TOKEN" --insecure -XGET $SERVER/api/v1/namespaces | jq -r '.items[].metadata.name');
do arr=($(curl -s -k -H "Authorization: Bearer $TOKEN" --insecure -XGET $SERVER/api/v1/namespaces/$each/pods | jq --arg node $HOSTNAME -r '.items[] | select(.spec.nodeName == $node) | .metadata.name'));
for i in ${arr[@]};
do curl -s --insecure -k -H "Authorization: Bearer $TOKEN" -XDELETE $SERVER/api/v1/namespaces/$each/pods/$i | grep "nodeName";
done
done
# Sleep 40 seconds because of default 30 seconds graceful period
sleep 40
@eshleebien
Copy link
Author

This cordons the node and drain its pods
Usage:

$ ./kube-api-drain.sh https://kubernetesapi:8000 service_account_token

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment