Skip to content

Instantly share code, notes, and snippets.

@thediveo
Created July 12, 2019 18:29
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 thediveo/c36a29f158d6174c1162c1c57be3b8a9 to your computer and use it in GitHub Desktop.
Save thediveo/c36a29f158d6174c1162c1c57be3b8a9 to your computer and use it in GitHub Desktop.
Starts local Kubernetes API proxy and creates a suitable context, runs application, then stops the proxy after the application has finished.
#!/bin/bash
CONTEXT="minikube"
PROXYCONTEXT="proxykube"
function cleanup {
kubectl config delete-context $PROXYCONTEXT 2>/dev/null
kubectl config delete-cluster $PROXYCONTEXT 2>/dev/null
}
# Start the host-local proxy to a Kubernetes remote API in the background and
# then parse its stdout output. As we later want to shut down the proxy again,
# we need its PID. But we only get the correct PID if we make the newly
# started subshell to replace itself with the kubectl process, instead of
# kubectl running as a child process inside the subshell. Thus, we need to
# "exec" kubectl inside the subshell.
#
# See also: https://ubuntuforums.org/showthread.php?t=979694
echo "starting API proxy for context:" "$CONTEXT"
exec 3< <(exec kubectl --context "$CONTEXT" proxy --port 0)
PROXYPID=$!
echo "API proxy PID:" $PROXYPID
# Wait for the proxy to report back the TCP port it has dynamically
# allocated...
PORT=
while read -r line; do
case "$line" in
"Starting to serve on "*)
PORT=$(echo "$line" | sed -r "s/^.*:([0-9]+)/\1/")
break
;;
*)
echo "kubectl problem:" "$line"
;;
esac
done <&3
# Has kubectl already terminated, closing its stdout? Then we never got a
# suitable port number...
if [ -z "$PORT" ]; then
echo "error: kubectl proxy failed"
exit 1
fi
echo "host-local Kubernetes API proxy at port:" $PORT
# Create a temporary context for, erm, unauthorized access via the proxy.
cleanup
kubectl config set-cluster $PROXYCONTEXT --server=http://127.0.0.1:$PORT
kubectl config set-credentials $PROXYCONTEXT
kubectl config set-context $PROXYCONTEXT --cluster=$PROXYCONTEXT --user=$PROXYCONTEXT
# Drain the proxy's stdout in the background as it has the need to talk to
# us...
coproc proxystdout {
while read -r line; do
echo "kubectl proxy:" "$line"
done
}
STOP=
function stop {
STOP="stop"
echo
}
trap stop SIGINT
for x in 1 2 3 4 5 6; do
if [ ! -z "$STOP" ]; then break; fi
echo -n "."
sleep 10
done
echo
trap - SIGINT
# Finally shut down the proxy again, after our test application has run to
# (in)completion.
echo "stopping API proxy PID $PID..."
kill $PROXYPID
cleanup
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment