Skip to content

Instantly share code, notes, and snippets.

@sandipb
Created August 9, 2023 01:38
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 sandipb/a0c888db9a140353a9d73994656abc55 to your computer and use it in GitHub Desktop.
Save sandipb/a0c888db9a140353a9d73994656abc55 to your computer and use it in GitHub Desktop.
export GCLOUD_TUNNEL_PID=/tmp/gcloud-tunnel-pid
function proxy_bastion() {
local BASTION_HOST="bastion-instance"
local GCP_ZONE="us-east4-a"
[[ -f $GCLOUD_TUNNEL_PID ]] && echo "File $GCLOUD_TUNNEL_PID exists. A previous tunnel might be active. Aborting." && return
set -x
gcloud compute ssh $BASTION_HOST --zone=$GCP_ZONE --verbosity=warning --tunnel-through-iap --ssh-flag='-D1080 -N' &
echo $! > $GCLOUD_TUNNEL_PID
export HTTPS_PROXY=socks5://localhost:1080
set +x
}
function proxy_bastion_end() {
[[ ! -f $GCLOUD_TUNNEL_PID ]] && echo "File $GCLOUD_TUNNEL_PID does not exist. Any current tunnel cannot be detected. Aborting." && return
PID=`cat $GCLOUD_TUNNEL_PID`
set -x
kill $PID
wait $PID
rm $GCLOUD_TUNNEL_PID
unset HTTPS_PROXY
set +x
}

Utility script to use an SSH tunnel to a GCP bastion host for reaching private kubernetes clusters

Assumptions

  1. There is a single bastion host(BASTION_HOST) in a given region - change in the proxy_bastion() function at the top.
  2. If there are multiple kubernetes clusters in different project, the bastion host in the current project has network ACLs to reach all of them.
  3. You will be running a single instance of the tunnel - the script hardcodes the path to a pid file, and a tunnel port. It should not be too difficult to modify the script to run the tunnel with a per shell pid file and an unique available port.
  4. You dont share the machine you are running this on! You are setting up a SOCKS proxy using your own credentials to a private network! This is just common sense!

Usage

$ source ~/.bashrc.kube_gcp_proxy

$ # To start tunnel in the current shell session
$ proxy_bastion
$ kubectl ....

$ # To end tunnel
$ proxy_bastion_end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment