Last active
May 21, 2021 11:40
-
-
Save evkuzin/f03d14515fcb9276b2471ecdd4d06a27 to your computer and use it in GitHub Desktop.
This file contains 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 | |
# gist to add/modify your ssh key to the google cloud project | |
# run bash <(curl -s URL_TO_THIS_RAW_GIST) -p PROJECT | |
TEMP_KEYS="/tmp/ssh-keys" | |
jq_not_installed () { | |
printf "\nplease install 'jq' util:\nbrew install jq\n\n" && exit 1 | |
} | |
while [[ $# -gt 0 ]] | |
do | |
key="$1" | |
case $key in | |
-p|--project) | |
PROJECT="$2" | |
shift | |
shift | |
;; | |
-k|--key) | |
SSH_KEY_PARAM="$2" | |
shift | |
shift | |
;; | |
-u|--user) | |
USER_PARAM="$2" | |
shift | |
shift | |
;; | |
esac | |
done | |
DEFAULT_USER=$(whoami) | |
USER="${USER_PARAM:-$DEFAULT_USER}" | |
DEFAULT_SSH_KEY="$HOME/.ssh/id_rsa" | |
SSH_KEY=${SSH_KEY_PARAM:-$DEFAULT_SSH_KEY} | |
if [ -z "$PROJECT" ] | |
then | |
printf "\nplease provide '-p PROJECT_NAME' where you want to set your ssh_key\n\n" | |
exit 1 | |
fi | |
if [ ! -f "$SSH_KEY.pub" ]; then | |
printf "\n$SSH_KEY.pub is not exist!, please add '-k key_name' for private key\n\n" | |
exit 1 | |
fi | |
jq -V > /dev/null 2>&1 || jq_not_installed | |
gcloud compute project-info describe --format='json' --project=$PROJECT | \ | |
jq -r '.commonInstanceMetadata.items[] | select(.key=="ssh-keys") | .value' | \ | |
grep -v -e "${USER}" -e "^$" > $TEMP_KEYS | |
printf "%s:%s\n" "${USER}" "$(cat ${SSH_KEY}.pub)" >> $TEMP_KEYS | |
if [ $(cat $TEMP_KEYS|wc -l ) -le "1" ] | |
then | |
printf "\nsomething is going wrong - probably you will rewrite all keys with your only please ask for help\n\n" | |
exit 1 | |
fi | |
gcloud compute project-info add-metadata --metadata-from-file ssh-keys=$TEMP_KEYS --project=$PROJECT | |
rm -f $TEMP_KEYS |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment