Skip to content

Instantly share code, notes, and snippets.

@Axelcouty
Created November 3, 2021 11:20
Show Gist options
  • Save Axelcouty/dd63efac3ac662693ce31f7fd12743b0 to your computer and use it in GitHub Desktop.
Save Axelcouty/dd63efac3ac662693ce31f7fd12743b0 to your computer and use it in GitHub Desktop.
kubectl port-forward to POD using labels, auto-reconnect to alive pods
#!/bin/bash
# Usage
# kfwd.sh [label=labelValue] [port]
echo $1:$2
labels=${1}
port=${2}
pid=""
pod=
while(true)
do
pods=($(kubectl get pods -l ${labels} --template '{{range .items}}{{ if and (not .metadata.deletionTimestamp) (not (eq .status.phase "Pending")) }}{{.metadata.name}}{{"\n"}}{{end}}{{end}}'))
if [[ ! -z ${pod} ]]; then
grepresult=$(echo "${pods[@]}" | grep ${pod})
found=$?
if [ ${found} -eq 1 ]; then
if [[ ! -z "${pid}" ]]; then
echo "Killing connection: ${pid} -> ${pod}"
(kill -s SIGINT "${pid}") # Run un subshell to avoid print. CAREFUL it also hides errors :)
pid=""
pod=""
fi
fi
fi
if [ "${#pods[@]}" -ne 0 ] && [ -z ${pod} ]; then
pod=${pods[0]}
echo "Connecting to ${pod}"
kubectl port-forward ${pod} ${port} &
pid="$!"
fi
sleep 3
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment