Skip to content

Instantly share code, notes, and snippets.

@feczo
Last active October 29, 2015 05:37
Show Gist options
  • Save feczo/91eef5c61d716957a0c5 to your computer and use it in GitHub Desktop.
Save feczo/91eef5c61d716957a0c5 to your computer and use it in GitHub Desktop.
Retrieve and re-create a TERMINATED compute engine instance from command line
PROJECT='named-enigma-222'
INSTANCE_NAME='test1'

STORE

gcloud compute instances describe --format=json ${INSTANCE_NAME} | egrep -v 'TERMINATED|"id":|"creationTimestamp":|"natIP":' >instance-config.json

DELETE

gcloud compute instances delete --keep-disk all -q ${INSTANCE_NAME}

RESTORE

# ${TOKEN} is an OAuth2 token you can get it by visiting
# eg. https://developers.google.com/apis-explorer/#p/compute/v1/compute.networks.list

open the network panel of developer tools view in Chrome

this is where you will see the token

# you find a token in ~/.config/gcloud/credentials as well, read he Oauth2 documentation for further details 
# https://developers.google.com/compute/docs/api/how-tos/authorization
ZONE=$(sed -n 's/.*"zone".*zones\/\(.*\)"/\1/p' instance-config.json)
curl --data "$(cat instance-config.json)" "https://www.googleapis.com/compute/v1/projects/${PROJECT}/zones/${ZONE}/instances" -H "Authorization: Bearer ${TOKEN}" -H "Content-Type: application/json"

ALTERNATIVE RESTORE REUSING THE DISK DURING CREATION

gcloud compute instances create ${INSTANCE} --disk name=${DISK_NAME} mode=rw boot=yes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment