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

Save money by launching compute instances with preset lifespans.

A great thing about the cloud is that it’s super easy to spin up new virtual machines (VMs). A less-great thing is that it’s also super easy to forget about all those machines you spun up, and find yourself paying for things you don’t really need. In this post, I’ll show how to use Google Compute Engine (GCE) to make VMs (also called “instances” in GCE) that delete themselves after a specified period of time, so you can fire them up, and forget about them.

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.

For additional flexibility, we can pass the self-destruct interval as a variable at instance creation time. This allows different lifespans for different purposes. We’ll use a GCE custom metadata field: when each instance is created, a field named SELF_DESTRUCT_INTERVAL_MINUTES is set on that instance. At startup, the instance will request its specified interval from the GCE metadata server, and will schedule its self-destruction accordingly.

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

You can modify the instance name and zone to suit your needs. This command has been tested on Ubuntu 16.04 and 18.04, and will probably work with other Linux distros. (A similar technique can likely be used to make self-deleting Windows instances.)

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.

In an upcoming post, I’ll describe just that: a CI pipeline that uses self-destructing VMs as dedicated, ephemeral test environments. Check back soon!