Skip to content

Instantly share code, notes, and snippets.

@masdeseiscaracteres
Last active April 6, 2023 19:40
Show Gist options
  • Save masdeseiscaracteres/6faa017c8ef04c33cc282a4b8b94ecda to your computer and use it in GitHub Desktop.
Save masdeseiscaracteres/6faa017c8ef04c33cc282a4b8b94ecda to your computer and use it in GitHub Desktop.
Bash script to SSH into the Google Cloud shell instance in your Google account
#!/usr/bin/env bash
# CLI for Google Cloud shell.
#
# Requirements:
# - gcloud
# - grep with Perl regexp support
# - curl
get_json_key () {
echo $2 | grep -Po '"'$1'": *"?\K.*?(?=[ ",}])'
# Use the one below if jq is installed
#echo $2 | jq -r $1
}
get_instance_info () {
ACCESS_TOKEN=$(gcloud auth print-access-token)
RESPONSE=$(curl -sS -H "Authorization: Bearer $ACCESS_TOKEN" https://cloudshell.googleapis.com/v1alpha1/users/me/environments/default)
STATE=$(get_json_key state "$RESPONSE")
echo "Cloud Shell instance is $STATE"
if [ $STATE == "DISABLED" ]; then
start_instance
fi
USERNAME=$(get_json_key sshUsername "$RESPONSE")
PORT=$(get_json_key sshPort "$RESPONSE")
HOST=$(get_json_key sshHost "$RESPONSE")
}
start_instance () {
RESPONSE=$(curl -sS -H "Authorization: Bearer $ACCESS_TOKEN" -X POST https://cloudshell.googleapis.com/v1alpha1/users/me/environments/default:start)
STATE=$(get_json_key state "$RESPONSE")
printf "Starting Cloud Shell instance..."
while [ $STATE != "RUNNING" ]
do
RESPONSE=$(curl -sS -H "Authorization: Bearer $ACCESS_TOKEN" https://cloudshell.googleapis.com/v1alpha1/users/me/environments/default)
STATE=$(get_json_key state "$RESPONSE")
sleep 0.1s
done
printf "[Done]"
}
case $1 in
login)
gcloud auth login
;;
ssh)
get_instance_info
shift
SSH_OPTIONS=$@
CMD="ssh -4 -p $PORT -i '~\.ssh\google_compute_engine' -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no $SSH_OPTIONS $USERNAME@$HOST"
echo $CMD
eval $CMD
;;
info)
get_instance_info
echo "STATE: $STATE"
echo "USERNAME: $USERNAME"
echo "HOST: $HOST"
echo "PORT: $PORT"
;;
*)
echo -e "Usage:\n $0 {login|ssh|info} [optional args]"
;;
esac
@masdeseiscaracteres
Copy link
Author

masdeseiscaracteres commented Mar 8, 2020

How to use it

  1. Authenticate
    ./cloud_shell.sh login

  2. SSH into the Google Cloud Shell machine (you must have an authorized private SSH key in ~\.ssh\google_compute_engine)
    ./cloud_shell.sh ssh

Dependencies

  • gcloud to start authentication
  • curl for HTTP requests
  • grep with Perl regular expressions support for naive JSON parsing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment