arrow_back

Clean Up Unused and Orphaned Persistent Disks

Join Sign in

Clean Up Unused and Orphaned Persistent Disks

1 hour 5 Credits

GSP648

Google Cloud self-paced labs logo

Overview

In this lab, you will use Cloud Functions and Cloud Scheduler to identify and clean up wasted cloud resources. In this case, you will schedule the Cloud Function to identify and clean up unattached and orphaned persistent disks.

What you'll do

  • Create two persistent disks.
  • Create a VM that uses one of the disks.
  • Detach the disk from the VM.
  • Review the Cloud Function code.
  • Deploy the Cloud Function.
  • Test the Cloud Function by using Cloud Scheduler jobs.

Architecture

The following diagram describes the architecture used in the first section of this lab, where you schedule a Cloud Function to identify and clean up unused and orphaned persistent disks.

Architecture diagram

Setup

In this section, you configure the infrastructure and identities required to complete the lab.

Before you click the Start Lab button

Read these instructions. Labs are timed and you cannot pause them. The timer, which starts when you click Start Lab, shows how long Google Cloud resources will be made available to you.

This hands-on lab lets you do the lab activities yourself in a real cloud environment, not in a simulation or demo environment. It does so by giving you new, temporary credentials that you use to sign in and access Google Cloud for the duration of the lab.

To complete this lab, you need:

  • Access to a standard internet browser (Chrome browser recommended).
Note: Use an Incognito or private browser window to run this lab. This prevents any conflicts between your personal account and the Student account, which may cause extra charges incurred to your personal account.
  • Time to complete the lab---remember, once you start, you cannot pause a lab.
Note: If you already have your own personal Google Cloud account or project, do not use it for this lab to avoid extra charges to your account.

How to start your lab and sign in to the Google Cloud Console

  1. Click the Start Lab button. If you need to pay for the lab, a pop-up opens for you to select your payment method. On the left is the Lab Details panel with the following:

    • The Open Google Console button
    • Time remaining
    • The temporary credentials that you must use for this lab
    • Other information, if needed, to step through this lab
  2. Click Open Google Console. The lab spins up resources, and then opens another tab that shows the Sign in page.

    Tip: Arrange the tabs in separate windows, side-by-side.

    Note: If you see the Choose an account dialog, click Use Another Account.
  3. If necessary, copy the Username from the Lab Details panel and paste it into the Sign in dialog. Click Next.

  4. Copy the Password from the Lab Details panel and paste it into the Welcome dialog. Click Next.

    Important: You must use the credentials from the left panel. Do not use your Google Cloud Skills Boost credentials. Note: Using your own Google Cloud account for this lab may incur extra charges.
  5. Click through the subsequent pages:

    • Accept the terms and conditions.
    • Do not add recovery options or two-factor authentication (because this is a temporary account).
    • Do not sign up for free trials.

After a few moments, the Cloud Console opens in this tab.

Note: You can view the menu with a list of Google Cloud Products and Services by clicking the Navigation menu at the top-left. Navigation menu icon

Activate Cloud Shell

Cloud Shell is a virtual machine that is loaded with development tools. It offers a persistent 5GB home directory and runs on the Google Cloud. Cloud Shell provides command-line access to your Google Cloud resources.

  1. Click Activate Cloud Shell Activate Cloud Shell icon at the top of the Google Cloud console.

When you are connected, you are already authenticated, and the project is set to your PROJECT_ID. The output contains a line that declares the PROJECT_ID for this session:

Your Cloud Platform project in this session is set to YOUR_PROJECT_ID

gcloud is the command-line tool for Google Cloud. It comes pre-installed on Cloud Shell and supports tab-completion.

  1. (Optional) You can list the active account name with this command:

gcloud auth list
  1. Click Authorize.

  2. Your output should now look like this:

Output:

ACTIVE: * ACCOUNT: student-01-xxxxxxxxxxxx@qwiklabs.net To set the active account, run: $ gcloud config set account `ACCOUNT`
  1. (Optional) You can list the project ID with this command:

gcloud config list project

Output:

[core] project = <project_ID>

Example output:

[core] project = qwiklabs-gcp-44776a13dea667a6 Note: For full documentation of gcloud, in Google Cloud, refer to the gcloud CLI overview guide.

Task 1. Enable APIs and clone repository

  1. In Cloud Shell, enable the Cloud Scheduler API:

    gcloud services enable cloudscheduler.googleapis.com
  2. Clone the repository:

    git clone https://github.com/GoogleCloudPlatform/gcf-automated-resource-cleanup.git && cd gcf-automated-resource-cleanup/
  3. Set environment variables and make the repository folder your $WORKDIR where you run all commands related to this lab:

    export PROJECT_ID=$(gcloud config list --format 'value(core.project)' 2>/dev/null) WORKDIR=$(pwd)

Task 2. Create persistent disks

  1. In Cloud Shell, navigate to the unattached-pd directory:

    cd $WORKDIR/unattached-pd
  2. Export the names of the disks as variables:

    export ORPHANED_DISK=orphaned-disk export UNUSED_DISK=unused-disk
  3. Create two disks:

    gcloud compute disks create $ORPHANED_DISK --project=$PROJECT_ID --type=pd-standard --size=500GB --zone=us-central1-a gcloud compute disks create $UNUSED_DISK --project=$PROJECT_ID --type=pd-standard --size=500GB --zone=us-central1-a

    This lab uses the us-central1 region, but you can choose a different region and refer to it consistently throughout the rest of the lab.

  4. Confirm that two disks were created:

    gcloud compute disks list

    Your output should look as follows:

    NAME LOCATION LOCATION_SCOPE SIZE_GB TYPE STATUS orphaned-disk us-central1-a zone 500 pd-standard READY unused-disk us-central1-a zone 500 pd-standard READY

Test completed task

Click Check my progress to verify your performed task. If you have successfully created a Persistent Disk, you will see an assessment score.

Create Persistent Disk

Task 3. Create a VM and inspect the disks

  1. In Cloud Shell, create an instance:

    gcloud compute instances create disk-instance \ --zone=us-central1-a \ --machine-type=n1-standard-1 \ --disk=name=$ORPHANED_DISK,device-name=$ORPHANED_DISK,mode=rw,boot=no
  2. Inspect the disk that was attached to the VM:

    gcloud compute disks describe $ORPHANED_DISK --zone=us-central1-a --format=json | jq

    The output is similar to the following:

    { "creationTimestamp": "2019-06-12T12:21:25.546-07:00", "id": "7617542552306904666", "kind": "compute#disk", "labelFingerprint": "42WmSpB8rSM=", "lastAttachTimestamp": "2019-06-12T12:24:53.989-07:00", "name": "orphaned-disk", "physicalBlockSizeBytes": "4096", "selfLink": "https://www.googleapis.com/compute/v1/projects/automating-cost-optimization/zones/us-central1-a/disks/orphaned-disk", "sizeGb": "500", "status": "READY", "type": "https://www.googleapis.com/compute/v1/projects/automating-cost-optimization/zones/us-central1-a/diskTypes/pd-standard", "users": [ "https://www.googleapis.com/compute/v1/projects/automating-cost-optimization/zones/us-central1-a/instances/disk-instance" ], "zone": "https://www.googleapis.com/compute/v1/projects/automating-cost-optimization/zones/us-central1-a" }

    In the preceding code sample, the following is important:

    • users identifies the VM that the disk is attached to.
    • lastAttachTimestamp identifies when the disk was last attached to a VM.

Test completed task

Click Check my progress to verify your performed task. If you have successfully created a VM instance with Persistent Disk, you will see an assessment score.

Create a VM instance with Persistent Disk
  1. Detach the orphaned disk from the VM:

    gcloud compute instances detach-disk disk-instance --device-name=$ORPHANED_DISK --zone=us-central1-a
  2. Inspect the orphaned disk:

    gcloud compute disks describe $ORPHANED_DISK --zone=us-central1-a --format=json | jq

    The output is similar to the following:

    { "creationTimestamp": "2019-06-12T12:21:25.546-07:00", "id": "7617542552306904666", "kind": "compute#disk", "labelFingerprint": "42WmSpB8rSM=", "lastAttachTimestamp": "2019-06-12T12:24:53.989-07:00", "lastDetachTimestamp": "2019-06-12T12:34:56.040-07:00", "name": "orphaned-disk", "physicalBlockSizeBytes": "4096", "selfLink": "https://www.googleapis.com/compute/v1/projects/automating-cost-optimization/zones/us-central1-a/disks/orphaned-disk", "sizeGb": "500", "status": "READY", "type": "https://www.googleapis.com/compute/v1/projects/automating-cost-optimization/zones/us-central1-a/diskTypes/pd-standard", "zone": "https://www.googleapis.com/compute/v1/projects/automating-cost-optimization/zones/us-central1-a" }

    In the preceding code sample, the following is important:

    • The disk doesn’t have users listed, which indicates that it isn’t currently in use.
    • There is now a lastDetachTimestamp entry, indicating when the disk was last detached from a VM and therefore, when it was last in use.
    • The lastAttachTimestamp field is still present.

Test completed task

Click Check my progress to verify your performed task. If you have successfully detached the orphaned disk from the VM, you will see an assessment score.

Detach the orphaned disk from the VM

Task 4. Review the Cloud Function code

  1. In Cloud Shell, output the section of the code that retrieves all persistent disks in the project:

    cat $WORKDIR/unattached-pd/main.py | grep "(request)" -A 12

    The output is as follows:

    def delete_unattached_pds(request): # get list of disks and iterate through it: disksRequest = compute.disks().aggregatedList(project=project) while disksRequest is not None: diskResponse = disksRequest.execute() for name, disks_scoped_list in diskResponse['items'].items(): if disks_scoped_list.get('warning') is None: # got disks for disk in disks_scoped_list['disks']: # iterate through disks diskName = disk['name'] diskZone = str((disk['zone'])).rsplit('/',1)[1] print (diskName) print (diskZone)

    The function uses the aggregatedList method to get all persistent disks in the Google Cloud project where it’s running and iterates through each of the disks.

  2. Output the section of the code that checks the lastAttachTimestamp field and deletes the disk if it doesn’t exist:

    cat $WORKDIR/unattached-pd/main.py | grep "handle never" -A 11

    The output is as follows:

    # handle never attached disk - delete it # lastAttachedTimestamp is not present try: if disk["lastAttachTimestamp"] is None: print ("none!") except KeyError: print ("disk " + diskName + " was never attached - deleting") deleteRequest = compute.disks().delete(project=project, zone=diskZone, disk=diskName) deleteResponse = deleteRequest.execute() waitForZoneOperation(deleteResponse, project, diskZone) print ("disk " + diskName + " was deleted") continue

    This section deletes the disk if lastAttachTimestamp isn’t present—meaning this disk was never in use.

  3. Output the section of the code that calculates the age of the disk if it’s orphaned, creates a snapshot of it, and deletes it:

    cat $WORKDIR/unattached-pd/main.py | grep "handle detached" -A 32

    The output is as follows:

    # handle detached disk - snapshot and delete # lastAttachTimestamp is present AND users is not present try: if disk['users'] is None and disk['lastDetachTimestamp'] is not None: print ("users is none") except KeyError: print ("disk " + diskName + " has no users and has been detached") detachTimestamp = dateutil.parser.parse(disk['lastDetachTimestamp']) detachedFor = pytz.utc.localize(datetime.utcnow()) - detachTimestamp print ("disk has been detached for " + str(detachedFor)) # update this for your preferred age if detachedFor.days > -1: # take a snapshot snapShotName = diskName + str(int(time.time())) print ("taking snapshot: " + snapShotName) snapshotBody = { "name": snapShotName } snapshotRequest = compute.disks().createSnapshot(project=project, zone=diskZone, disk=diskName, body=snapshotBody) snapshotResponse = snapshotRequest.execute() waitForZoneOperation(snapshotResponse, project, diskZone) print ("snapshot completed") # delete the disk print ("deleting disk " + diskName) deleteRequest = compute.disks().delete(project=project, zone=diskZone, disk=diskName) deleteResponse = deleteRequest.execute() waitForZoneOperation(deleteResponse, project, diskZone) print ("disk " + diskName + " was deleted") continue

    This section of code is used when the disk does have users listed and lastDetachTimestamp is present, which means the disk is currently not in use, but was used at some point in time. In this case, the Cloud Function creates a snapshot of the disk to retain data and then deletes the disk.

  4. In Cloud Shell, click Open Editor to open the Cloud Shell Editor to edit the main.py file.

Note: If prompted, click Open in New Window.
  1. Navigate to gcf-automated-resource-cleanup\unattached-pd.

  2. Open main.py.

  3. Edit line 15 of the file and replace automating-cost-optimization with your project id (it should look similar to):

    project = 'qwiklabs-gcp-b5dbc291a25a68db'
  4. Save the file by clicking File > Save.

Task 5. Deploy the Cloud Function

  1. In Cloud Shell, deploy the Cloud Function:

    gcloud functions deploy delete_unattached_pds --trigger-http --runtime=python39 Note: Type y when asked: Allow unauthenticated invocations of new function [delete_unattached_pds]? (y/N)? Note: Deploying a cloud function can take 2-5 minutes, depending on region.
  2. Capture the trigger URL of the Cloud Function as an environment variable:

    export FUNCTION_URL=$(gcloud functions describe delete_unattached_pds --format=json | jq -r '.httpsTrigger.url')

Test completed task

Click Check my progress to verify your performed task. If you have successfully deployed the Cloud Function, you will see an assessment score.

Deploy the Cloud Function

Task 6. Schedule and test the Cloud Function

  1. In Cloud Shell, create an App Engine app to use Cloud Scheduler:

gcloud app create --region us-central
  1. In Cloud Shell, create a Cloud Scheduler task to run the Cloud Function at 2 AM every night:

    gcloud scheduler jobs create http unattached-pd-job \ --schedule="* 2 * * *" \ --uri=$FUNCTION_URL \ --location=us-central1

Test completed task

Click Check my progress to verify your performed task. If you have successfully created a Cloud Scheduler task to run the Cloud Function, you will see an assessment score.

Create a Cloud Scheduler task to run the Cloud Function
  1. Test the job by manually triggering it:

    gcloud scheduler jobs run unattached-pd-job
  2. Confirm that a snapshot of the orphaned disk was created:

    gcloud compute snapshots list

    The output is similar to the following:

    NAME DISK_SIZE_GB SRC_DISK STATUS orphaned-disk1560455894 500 us-central1-a/disks/orphaned-disk READY
  3. Confirm that the unused disk and the orphaned disk were deleted:

    gcloud compute disks list

    The output is similar to the following:

    NAME LOCATION LOCATION_SCOPE SIZE_GB TYPE STATUS disk-instance us-central1-a zone 10 pd-standard READY orphaned-disk us-central1-a zone 500 pd-standard READY unused-disk us-central1-a zone 500 pd-standard READY

Test completed task

Click Check my progress to verify your performed task. If you have successfully tested the job by manually triggering it, you will see an assessment score.

Test the job by manually triggering it

Congratulations!

In this lab, you completed the following tasks:

  • Created two persistent disks.

  • Created a VM that uses one of the disks.

  • Detached the disk from the VM.

  • Reviewed the Cloud Function code.

  • Deployed the Cloud Function.

  • Tested the Cloud Function by using Cloud Scheduler jobs.

Finish your quest

This self-paced lab is part of the Optimizing your Google Cloud Costs quest. A quest is a series of related labs that form a learning path. Completing this quest earns you a badge to recognize your achievement. You can make your badge or badges public and link to them in your online resume or social media account. Enroll in this quest or any quest that contains this lab and get immediate completion credit. See the Google Cloud Skills Boost catalog to see all available quests.

Take your next lab

Continue your Quest with Network Tiers - Optimizing Network Spend or check out these suggestions:

Google Cloud training and certification

...helps you make the most of Google Cloud technologies. Our classes include technical skills and best practices to help you get up to speed quickly and continue your learning journey. We offer fundamental to advanced level training, with on-demand, live, and virtual options to suit your busy schedule. Certifications help you validate and prove your skill and expertise in Google Cloud technologies.

Manual Last Updated July 19, 2022

Lab Last Tested March 21, 2022

Copyright 2022 Google LLC All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.