Skip to content

Instantly share code, notes, and snippets.

@boxrick
Created October 29, 2018 17:59
Show Gist options
  • Save boxrick/b6e341f072bde559ca8840f9a26decaf to your computer and use it in GitHub Desktop.
Save boxrick/b6e341f072bde559ca8840f9a26decaf to your computer and use it in GitHub Desktop.
Script to cleanup Google Cloud - GCP - virtual machine images based on project and number of desired images
#!/bin/bash
# Script to cleanup GCP virtual machine images
# How many images of this family do we wish to retain
desired_images=8
image_project="PROJECTHERE"
clean_images()
{
# Function to clean up images, set the default family to megatron base
# Calculate how many images there are and how many images we need to delete to get to our desired image amount
number_of_images=$(gcloud compute images list --filter="family=( ${image_family} )" --project=${image_project} | wc -l | xargs)
images_to_delete=$((${number_of_images}-${desired_images}))
echo ""
echo "Total found images in ${image_family} family - $number_of_images"
# Working variables
loop=0
# Iterate over all the listed images in family and project
for image in $(gcloud compute images list --sort-by "creationTimestamp" --filter="family=( ${image_family} )" --project=${image_project} --format="value(NAME)" | cut -f1); do
if [ $loop -ge $images_to_delete ]; then
if [ $loop == 0 ]; then
echo "No images to delete"
fi
echo "Images processed"
echo ""
break
fi
let "loop++"
# Delete the image with no confirmation
echo "deleting $image"
gcloud compute images delete --project ${image_project} -q ${image}
done
}
clean_images "IMAGE-FAMILY-NAME-HERE"
@boxrick
Copy link
Author

boxrick commented Oct 29, 2018

The documentation is slightly obscure on this, it should be fairly simple to do but these things never are. Hopefully this will help someone out!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment