-
-
Save dlenski/4667a9bf2caecc7bd30589f0911e8db7 to your computer and use it in GitHub Desktop.
SSH ProxyCommand wrapper script for 'gcloud compute start-iap-tunnel'
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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