How to make a self-destructing VM on Google Cloud Platform

Save money by launching compute instances with preset lifespans.

How it works

This technique makes use of GCE’s Startup Script feature: when creating an instance, we provide a startup script in the metadata-from-file argument. As soon as the instance finishes booting, it executes the script, which begins the countdown to deletion. To achieve that, the script schedules a task using the linux at command: at the scheduled time, that task will instruct the GCE API to delete its host instance.

Try it out

In this GitHub repo, you‘ll find the startup script, and a sample gcloud command to create a self-destructing instance. Here’s a portion of the command, with the tasty bits in bold:

gcloud compute instances create \
self-destructing-vm \
[...] \
--metadata SELF_DESTRUCT_INTERVAL_MINUTES=2 \
--metadata-from-file startup-script=self-destruct.sh

But WHY IN THE WORLD would I do that?!?

Because it’s fun! Like blowing bubbles and watching them pop. But also: sometimes we need assurance that resources we provision will be deprovisioned — so they don’t hang around forever, costing money. Perhaps, for Continuous Integration: as part of a CI pipeline, we can create a one-time-use environment and run tests against it. If the pipeline fails (as pipelines do), we know the environment will be automatically deleted in a reasonable timeframe.

--

--

A collection of technical articles and blogs published or curated by Google Cloud Developer Advocates. The views expressed are those of the authors and don't necessarily reflect those of Google.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Dave Stanke

DevOps Advocate at Google. My home is in Jersey City. My office is in New York. My opinions are all over the map, and may not reflect those of my employer.