#!/bin/bash # Get api server and node name for kubelet context API_SERVER=$(kubectl --kubeconfig /root/.kube/config config view -o json | jq -r '.clusters[].cluster.server') NODE_NAME=$(kubectl --kubeconfig /root/.kube/config config view -o json | jq -r '.["current-context"]' | sed -e 's/system:node://' -e 's/@.*//') if [ -z "$API_SERVER" ] || [ -z "$NODE_NAME" ]; then echo "Could not find kube context. Abort." exit 1 fi # Delete all node status as we are not allowed to cordon ourselfs curl -s --cacert /etc/kubernetes/pki/ca.crt \ --cert /var/lib/kubelet/pki/kubelet-client-current.pem \ -H "Content-Type: application/json-patch+json" -X PATCH \ $API_SERVER/api/v1/nodes/$NODE_NAME/status \ --data '[ { "op": "replace", "path": "/status/conditions", "value": []}]' >/dev/null # Loop through all local pods EVICTED="" while read NAMESPACE NAME; do # get pod owner OWNER=$(curl -s --cacert /etc/kubernetes/pki/ca.crt \ --cert /var/lib/kubelet/pki/kubelet-client-current.pem \ -H 'Content-type: application/json' \ "$API_SERVER"/api/v1/namespaces/"$NAMESPACE"/pods/"$NAME" | jq -r '.metadata.ownerReferences[].kind') [ -n "$OWNER" ] || continue # skip over DS and static manifests [[ "$OWNER" =~ (DaemonSet|Node) ]] && continue JSON='{ "apiVersion": "policy/v1", "kind": "Eviction", "metadata": { "name": "'$NAME'", "namespace": "'$NAMESPACE'" } }' HTTP_CODE=$(curl -o /dev/null -s -w "%{http_code}\n" --cacert /etc/kubernetes/pki/ca.crt \ --cert /var/lib/kubelet/pki/kubelet-client-current.pem \ -X POST -H 'Content-type: application/json' \ --data-raw "$JSON" \ "$API_SERVER"/api/v1/namespaces/"$NAMESPACE"/pods/"$NAME"/eviction) if [ "$HTTP_CODE" = "201" ]; then echo "Evicted $NAMESPACE/$NAME" EVICTED="$EVICTED $NAME" else echo "Error trying to evict $NAMESPACE/$NAME" fi done < <(crictl pods -o json | jq -r '.items[].metadata | {name,namespace} | .namespace + " " + .name') # Stop all successfully evicted pods in parallel and wait till all stopped for name in $EVICTED; do crictl stopp $(crictl pods -o json --name $name | jq -r '.items[].id') & done wait