Skip to content

Instantly share code, notes, and snippets.

@jomido
Created October 13, 2017 14:52
Show Gist options
  • Save jomido/2703d6397f45826a93cd0f4f74dcde46 to your computer and use it in GitHub Desktop.
Save jomido/2703d6397f45826a93cd0f4f74dcde46 to your computer and use it in GitHub Desktop.
Idempotent Gcloud Compute Create
#!/bin/bash
# BEGIN SANITY BOX------------------------------------------
set -e # immediately exit if any command fails |
set -u # immediately fail on undefined variables |
set -o pipefail # show error of last failed command |
IFS=$'\n\t' # control what word splitting means |
# END SANITY BOX--------------------------------------------
# delete
# echo Y | gcloud compute instances delete $(NAME) --zone=$(ZONE)
CURRENT_INSTANCES=$(gcloud compute instances list | grep one-off-script-box)
NAME=one-off-script-box-$(uuidgen | cut -c 1-6 | tr '[:upper:]' '[:lower:]')
ZONE=us-west1-c
IMAGE=cloud-train
SCOPES=https://www.googleapis.com/auth/devstorage.full_control,https://www.googleapis.com/auth/datastore
if [ -z "$CURRENT_INSTANCES" ]
then
echo "> creating '${NAME}' in zone '${ZONE}'"
gcloud compute instances create $NAME \
--description a-one-off-script-box \
--machine-type f1-micro \
--zone $ZONE \
--image $IMAGE \
--scopes $SCOPES
# --image-project debian-cloud \
else
echo "Instances already exist:"
echo $CURRENT_INSTANCES
CURRENT_INSTANCES=(${CURRENT_INSTANCES[@]})
FIRST_INSTANCE=${CURRENT_INSTANCES[0]}
NAME=$(echo $FIRST_INSTANCE | awk '{print $1}')
ZONE=$(echo $FIRST_INSTANCE | awk '{print $2}')
fi
echo "> entering '${NAME}' in zone '${ZONE}'"
gcloud compute ssh $NAME --zone=$ZONE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment