Skip to content

Instantly share code, notes, and snippets.

@erikdubbelboer
Last active January 12, 2018 05:12
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erikdubbelboer/bc290b5cfa61d8747f70 to your computer and use it in GitHub Desktop.
Save erikdubbelboer/bc290b5cfa61d8747f70 to your computer and use it in GitHub Desktop.
Google Cloud shell wrappers
#!/bin/bash
# Copy files from and to Google Compute Engine instances
# Automatically looks up the correct zone and uses ~/.ssh/id_rsa
# Usage
# gscp ./some.file some-instance-name:some-directory
# gscp some-instance-name:some-directory ./some.file
for project in $(gcloud projects list | grep -v PROJECT_ID | cut -d' ' -f 1); do
PROJECT=$project
ZONE=`gcloud compute instances list --project=$PROJECT | grep "${1/:*/}\s" | awk '{ print $2 }'`
if [[ -z "$ZONE" ]]; then
if [[ $2 == *:* ]]; then
ZONE=`gcloud compute instances list --project=$PROJECT | grep "${2/:*/}\s" | awk '{ print $2 }'`
fi
fi
if [[ ! -z $ZONE ]]; then
break
fi
done
if [[ -z $ZONE ]]; then
echo "server does not exist"
exit 1
fi
echo gcloud compute scp --ssh-key-file=~/.ssh/id_rsa --project=$PROJECT --zone=$ZONE "$@"
gcloud compute scp --ssh-key-file=~/.ssh/id_rsa --project=$PROJECT --zone=$ZONE "$@"
#!/bin/bash
# Execute a command on all Google Compute Engine instances matching a pattern.
# Automatically looks up the correct zone, sets up ssh-agent forwarding and uses ~/.ssh/id_rsa
# Usage:
# gsshfor pattern command [arg [arg]...]
# Example:
# gsshfor some-prefix df -h
eval `ssh-agent`
trap "kill $SSH_AGENT_PID" EXIT
for i in `gcloud compute instances list | grep $1 | awk '{ print $1 }'`; do
echo $i
ZONE=`gcloud compute instances list | grep $i | awk '{ print $2 }'`
gcloud compute ssh --ssh-key-file=~/.ssh/id_rsa --ssh-flag="-A" --zone=$ZONE $i -- "${@:2}"
done
#!/bin/bash
# Replacement for ssh to Google Compute Engine instances
# Automatically looks up the correct zone, sets up ssh-agent forwarding and uses ~/.ssh/id_rsa
# Usage:
# gssh name [command] [arg [arg]...]
# Example:
# gssh some-instance-name
# gssh some-instance-name -- df -h
for project in $(gcloud projects list | grep -v PROJECT_ID | cut -d' ' -f 1); do
PROJECT=$project
ZONE=$(gcloud compute instances list --project=$PROJECT | grep $1 | head -n 1 | awk '{ print $2 }')
if [[ ! -z $ZONE ]]; then
break
fi
done
if [[ -z $ZONE ]]; then
echo "$2 does not exist"
exit 1
fi
eval $(ssh-agent -s)
trap "kill $SSH_AGENT_PID" EXIT
gcloud compute ssh --project=$PROJECT --ssh-key-file=~/.ssh/id_rsa --ssh-flag="-A" --zone=$ZONE "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment