Skip to content

Instantly share code, notes, and snippets.

@dlenskiSB
Last active July 16, 2024 20:34
Show Gist options
  • Save dlenskiSB/5ddeac691f316f84a693c5db16c3ba7e to your computer and use it in GitHub Desktop.
Save dlenskiSB/5ddeac691f316f84a693c5db16c3ba7e to your computer and use it in GitHub Desktop.
SSH ProxyCommand wrapper script for 'gcloud compute start-iap-tunnel'
#!/bin/bash
set -eo pipefail
if [[ $# == 0 ]]; then
cat <<EOF
usage: $(basename $0) [ARGUMENTS FOR 'gcloud compute start-iap-tunnel']
For some reason, 'gcloud compute start-iap-tunnel' lacks a mode where it can
be used as a ProxyCommand for SSH (e.g. proxy between stdin and stdout), so
we have to implement it ourselves.
With this script in your path, you can take a GCP instance URL as follows:
https://console.cloud.google.com/compute/instancesDetail/zones/\${GCP_ZONE}/instances/\${GCP_INSTANCE_NAME}?project=\${GCP_PROJECT}
Then add a section like this to your ~/.ssh/config:
Host \${MY_ALIAS}
HostName \${GCP_INSTANCE_NAME}
ProxyCommand $(basename $0) %h %p --project=\$GCP_PROJECT --zone=\$GCP_ZONE
And then simply use 'ssh \${MY_ALIAS}' to ssh to your GCP instance.
EOF
exit 1
fi
portfifo="$(mktemp -u)"
mkfifo -m 600 "$portfifo" # See https://unix.stackexchange.com/a/29918/58453 for why this is not hijackable
# Run 'gcloud compute start-iap-tunnel' in the background.
# Its first line of output should be 'Picking local unused port [NNNNN].'
PYTHONUNBUFFERED=1 CLOUDSDK_PYTHON_SITEPACKAGES=1 gcloud compute start-iap-tunnel "$@" --local-host-port=localhost:0 > "$portfifo" &
trap "kill $!" EXIT
# Read the port, then start nc
IFS='[]' read _ port _ < "$portfifo" && /bin/rm -f "$portfifo"
echo "Got IAP port $port (and dropped FIFO $portfifo)" >&2
nc localhost "$port"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment