Skip to content

Instantly share code, notes, and snippets.

@thanosa75
Created May 23, 2022 10:45
Show Gist options
  • Save thanosa75/457d035e332c4a5862bc1d62093f8716 to your computer and use it in GitHub Desktop.
Save thanosa75/457d035e332c4a5862bc1d62093f8716 to your computer and use it in GitHub Desktop.
Create a socket tunnel via a pod on a kubernetes namespace
#!/usr/bin/env bash
#
# A simple 'tunnel-via-pod' mechanism, that allows you to test pod or
# namespace connectivity to specific services.
# See the help() function for more documentation
#
# USE -AS-IS- NO LICENSE PROVIDED
# requires kubectl in classpath and a valid $TMPDIR location.
set -e
function help {
echo "tunnel via a pod"
echo ""
echo " $0 <localport> <containerport> <remotehost> <remoteport> {podname}"
echo ""
echo " localport - the port that appears on the local machine > 1024 ;"
echo " containerport - the port that appears on the pod > 1024 ;"
echo " remotehost - host to connect to;"
echo " remoteport - port to connect to."
echo ""
echo " Sets up a tunnel, from the localhost:localport -> pod:containerport -> remotehost:remoteport"
echo " To stop the tunnel, use ctrl-c will stop and delete the pod."
echo ""
}
if [ "xx$1" == "xx" ];
then
help
exit 250
fi
TMPNAME="$5"
TEMP_POD_NAME=${TMPNAME:-jumphost-${USER}-${RANDOM}}
LOCAL_PORT="$1"
CONTAINER_PORT="$2"
REMOTE_HOST="$3"
REMOTE_PORT="$4"
function cleanup {
echo ""
echo "cleaning up..."
kubectl delete "pod/$TEMP_POD_NAME" --grace-period 1 --wait=false
echo "$?"
}
trap cleanup EXIT
# heredoc
cat << EOF > $TMPDIR/deploy$TEMP_POD_NAME.yaml
apiVersion: v1
kind: Pod
metadata:
name: $TEMP_POD_NAME
spec:
containers:
- name: $TEMP_POD_NAME
image: alpine/socat
imagePullPolicy: Always
command: [ "socat" ]
args: [ "-v", "-d", "tcp-listen:$CONTAINER_PORT,fork,reuseaddr", "tcp-connect:$REMOTE_HOST:$REMOTE_PORT" ]
resources:
limits:
cpu: 100m
memory: 80Mi
securityContext:
runAsGroup: 999
runAsUser: 999
EOF
kubectl apply -f "$TMPDIR/deploy$TEMP_POD_NAME.yaml"
kubectl wait --for=condition=Ready "pod/$TEMP_POD_NAME"
rm -f "$TMPDIR/deploy$TEMP_POD_NAME.yaml"
kubectl port-forward "pod/$TEMP_POD_NAME" "$LOCAL_PORT:$CONTAINER_PORT"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment