Skip to content

Instantly share code, notes, and snippets.

@Nezteb
Last active March 29, 2023 04:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nezteb/738c962089dec067ab79c002d02a3ebe to your computer and use it in GitHub Desktop.
Save Nezteb/738c962089dec067ab79c002d02a3ebe to your computer and use it in GitHub Desktop.
A simple shell wrapper around socat for tunneling a TCP port in a Kubernetes cluster.
kubeforward() {
# https://yuku.takahashi.coffee/blog/2020/07/connect-to-a-resource-behind-a-k9s-cluster-from-local-machine
# https://hub.docker.com/r/alpine/socat
if [[ ($# -ne 3 && $# -ne 4) ]]; then
echo "Usage: kubeforward <endpoint> <endpoint_port> <local_port> [<label>]"
return
fi
KUBE_NAMESPACE="default"
ENDPOINT_ADDRESS=$1 # URL to service you want to access
ENDPOINT_PORT=$2
LOCAL_PORT=$3
LABEL=$4
TUNNEL_NAME="$(whoami)-tunnel-${LABEL:-$LOCAL_PORT}"
if kubectl get pod "$TUNNEL_NAME" &>/dev/null; then
echo "Pod already exists, deleting first: $TUNNEL_NAME"
kubectl delete pod "$TUNNEL_NAME" &>/dev/null
fi
# Original blog post added `--expose=true`, but we don't need a service for this
kubectl \
-n "$KUBE_NAMESPACE" \
run "$TUNNEL_NAME" \
--image=alpine/socat \
--rm \
-it \
--tty \
--port="$LOCAL_PORT" \
"tcp-listen:$LOCAL_PORT,fork,reuseaddr" \
"tcp-connect:$ENDPOINT_ADDRESS:$ENDPOINT_PORT" &
RUN_PID=$!
until [ "$(kubectl get pod "$TUNNEL_NAME" -o jsonpath="{.status.containerStatuses[0].started}")" = "true" ]; do
echo "Pod not ready yet: $TUNNEL_NAME"
sleep 1
done
# NOTE: Only one port-forward can be active at a time
kubectl port-forward "pod/$TUNNEL_NAME" "$LOCAL_PORT:$LOCAL_PORT" &
PF_PID=$!
# https://superuser.com/a/1644785
echo -e "To stop tunnel:\n\tkill -CONT $RUN_PID && kill $PF_PID"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment