Skip to content

Instantly share code, notes, and snippets.

@umutbasal
Last active February 4, 2024 14:02
Show Gist options
  • Save umutbasal/98369715ce0901aab79ede0d345210bc to your computer and use it in GitHub Desktop.
Save umutbasal/98369715ce0901aab79ede0d345210bc to your computer and use it in GitHub Desktop.
# usage pods_on.sh <node1> <node2> <label1=value1> <label2=value2> <...> <kubectl_flags>
# example pods_on.sh node1 "ingress in (true)" -o wide
flags=(); nodes=(); k=true
for arg in "${@}"; do
if [[ $arg == "-"* ]]; then k=false; fi
$k && { [[ $arg == *"="* || $arg == *"("* ]] && nodes+=($(kubectl get nodes -l "$arg" -o jsonpath='{.items[*].metadata.name}')) || nodes+=($arg); } || flags+=($arg)
done
nodes=($(echo "${nodes[@]}" | tr ' ' '\n' | sort -u | tr '\n' ' '))
[ ${#nodes[@]} -eq 0 ] && { echo "No nodes found"; exit 1; }
[ ${#nodes[@]} -eq 1 ] && { kubectl get pods -A --field-selector spec.nodeName=${nodes[0]} ${flags[@]}; exit 0; }
# if multiple nodes, build a field selector with neq grep -v -E "(node1|node2)"
excludedNodes=($(kubectl get nodes -o jsonpath='{.items[*].metadata.name}' | tr ' ' '\n' | grep -v -E "($(echo ${nodes[@]} | tr ' ' '|'))" | tr '\n' ' '))
param=$(printf "spec.nodeName!=%s," "${excludedNodes[@]}" | sed 's/,$//')
kubectl get pods -A --field-selector $param ${flags[@]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment