Last active
March 30, 2021 08:56
-
-
Save starkfell/2c2ac0ce910e85ea6ef93159c9ba5ff9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# | |
# Name: delete-unattached-managed-disks.py | |
# | |
# Author: Ryan Irujo | |
# | |
# Description: Python script for removing unattached managed disks in an Azure Subscription. | |
# | |
# Notes: You must already be logged into an Azure Subscription for this script to work. | |
# | |
# Syntax: ./delete-unattached-managed-disks.py | |
import subprocess | |
import sys | |
# [yes] and [no] options used throughout the script. | |
yes = {'yes','y'} | |
no = {'no','n'} | |
# Retrieving the current targeted Azure Subscription. | |
try: | |
process = subprocess.Popen(['az','account','show','--query','name','--output','tsv'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT,encoding="utf-8") | |
queryAzSub = process.communicate()[0].strip() | |
except: | |
print (queryAzSub) | |
# Verifying the correct Azure Subscription is targeted or exiting script. | |
confirm = input("Targeting Azure Subscription [{}]. Do you wish to continue? [yes] or [no] ".format(queryAzSub)) | |
if confirm in yes: | |
print("Continuing.") | |
elif confirm in no: | |
print("Exiting.") | |
quit() | |
else: | |
print("Exiting.") | |
quit() | |
# JMESPath Query used to return only unattached managed disks in the Azure Subscription. | |
diskQuery = '''[?managedBy==`null`].[id]''' | |
# Checking for unattached managed Disks in the target Azure Subscription. | |
try: | |
process = subprocess.Popen(['az','disk','list','--query',diskQuery,'-o','tsv'],stdout=subprocess.PIPE,stderr=subprocess.STDOUT,encoding="utf-8") | |
diskQueryResults = process.stdout.readlines() | |
except: | |
print (diskQueryResults) | |
# Deleting Disks. | |
for disk in diskQueryResults: | |
confirm = input("{} is no longer in use. Do you wish to delete it? [yes] or [no] ".format(disk)) | |
if confirm in yes: | |
try: | |
process = subprocess.Popen(['az','disk','delete','--ids',disk,'--yes'],stdout=subprocess.PIPE,stderr=subprocess.STDOUT,encoding="utf-8") | |
deleteDiskResult = process.communicate()[0] | |
except: | |
print (deleteDiskResult) | |
finally: | |
if "ERROR" in deleteDiskResult: | |
print(deleteDiskResult) | |
else: | |
print("The disk was successfully deleted.") | |
elif confirm in no: | |
print("Skipping deletion of disk {}. ".format(disk)) | |
else: | |
print("Exiting.") | |
quit() | |
print("Process Complete.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment