Last active
April 6, 2023 19:40
-
-
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
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
#!/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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How to use it
Authenticate
./cloud_shell.sh login
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 authenticationcurl
for HTTP requestsgrep
with Perl regular expressions support for naive JSON parsing