Delete all unattached Google Persistent Disks in a project

5/11/2021

In GKE, the Reclaim Policy of my PersistentVolume is set to Retain, in order to prevent unintentional data removal. However, sometimes, after the deletion of some PersistentVolumes, I'd like to remove the associated Google Persistent Disks manually. Deleting the Google Persistent Disks using the web UI (i.e. Google Cloud Console) is time-consuming, that's why I'd like to use a gcloud command to remove all Google Persistent Disks that are not attached to a GCP VM instance. Could somebody please provide me this command?

-- Fabrice Jammes
gcloud
google-kubernetes-engine
kubernetes

3 Answers

5/15/2021

This one work fine, assuming you are in the correct region/zone (use gcloud config set compute/zone <my-zone>):

gcloud compute disks delete $(gcloud compute disks list --filter="-users:*" --format "value(name)")
-- Fabrice Jammes
Source: StackOverflow

5/11/2021

You can use the gcloud compute disks delete command in cloud shell to delete all the disks that are not attached in a gcp vm instance.

gcloud compute disks delete DISK_NAME DISK_NAME … GCLOUD_WIDE_FLAG …

you can provide disknames through this command to delete them.

disk delete

-- Sandeep Mohanty
Source: StackOverflow

5/11/2021

The link that @sandeep-mohanty includes suggests that only non-attached disks are deleted by the command.

Assuming (!) that to be true (check before you delete), you can enumerate a project's disks and then delete the (not attached) disks with:

PROJECT=[[YOUR-PROJECT]]

# Get PAIRS (NAME,ZONE) for all disk in ${PROJECT}
# Using CSV  (e.g. my-disk,my-zone) enables IFS parsing (below)
PAIRS=$(\
  gcloud compute disks list \
  --project=${PROJECT} \
  --format="csv[no-heading](name,zone.scope())")

# Iterate over the PAIRS
for PAIR in ${PAIRS}
do
  # Extract values of NAME,ZONE from PAIR
  IFS=, read NAME ZONE <<< ${PAIR}
  # Describe
  printf "Attempting to delete disk: %s [%s]\n" ${NAME} ${ZONE}
  # Deleting a disks should only succeed if not attached
  gcloud compute disks delete ${NAME} \
  --zone=${ZONE} \
  --project=${PROJECT} \
  --quiet
done

NOTE In the unlikely event that Google changes the semantics of gcloud compute disks delete to delete attached disks, this script will delete every disk in the project.

-- DazWilkin
Source: StackOverflow