GCP’s Self-Destructive VMs
VM Instances self-destructive feature in GCP allows you to maintain the cost-effectiveness of the Cloud usage of any Organization.
Are you still paying for unused VM instances which you have once spun-up and forgotten about?
Google Cloud Platform (GCP) comes up with VM instances that can self-destroy once the work is done, so no more paying for unused instances.
This is how it works:
- With the use of GCE’s (Google Compute Engine) Startup Script, you get a script argument while creating an instance.
- As soon as the instance is created and booted, it executes the script and starts the countdown for self-destruction.
- The script schedules a task using the Linux command, which instructs the GCE’s API to delete its host instance.
- This can also be done as different lifespans to different instances for different purposes.
How to create self-destructive VMs:
- Provide a Startup Script in the “metadata-from-file” argument. Sample startup script:
gcloud compute instances create \
self-destructing-vm \ [...] \
--metadata SELF_DESTRUCT_INTERVAL_MINUTES=2 \
After the instance is booted the script schedules a Linux “at” command, to instruct the GCE API for deletion.
- To allow different lifespans by using GCE’s custom metadata when each instance is created, a field named “SELF_DESTRUCT_INTERVAL_MINUTES” is set. At the start, the instance will request its specified interval from the GCE metadata server and will schedule its deletion.
- Create a startup script by using the command - sudo nano “self-destruct.sh”.
- Copy and paste the below code to create the script:
# use this as a startup script for a compute instance and it will self-destruct after specified interval
# (default = 2 hours)
# retrieve interval from metadata service (if available)
TIMEOUT_FROM_METADATA=$(curl -H Metadata-Flavor:Google http://metadata.google.internal/computeMetadata/v1/instance/attributes/SELF_DESTRUCT_INTERVAL_MINUTES -s)
if [ -z "$TIMEOUT_FROM_METADATA" ]
# schedule the instance to delete itself
echo "gcloud compute instances delete $(hostname) --zone \
$(curl -H Metadata-Flavor:Google http://metadata.google.internal/computeMetadata/v1/instance/zone -s | cut -d/ -f4) -q" | at Now + $TIMEOUT Minutes
- Upon completion of this process, it will execute the command for creating a preemptive VM, as mentioned earlier.
A preemptible VM is an instance that you can create and run at a much lower cost than normal instances. However, Compute Engine might terminate or preempt these instances if it requires access to those resources for any other task. Preemptible instances will reduce your Compute Engine costs significantly if your applications are fault-tolerant and can withstand instance preemptions.