|
| 1 | +import os |
| 2 | +from datetime import datetime |
| 3 | +import argparse |
| 4 | +import asyncio |
| 5 | +from dotenv import load_dotenv |
| 6 | +from azure.identity import DefaultAzureCredential |
| 7 | +from azure.mgmt.resource.resources.v2022_09_01 import ResourceManagementClient |
| 8 | +from azure.core.exceptions import ResourceNotFoundError |
| 9 | +from resource_graph_query import run_azure_rg_query |
| 10 | + |
| 11 | +async def list_resource_groups_with_temporary_tag(subscription_id: str): |
| 12 | + """ |
| 13 | + List the resource groups in authenticated subscriptions with Temporary tag value as TRUE |
| 14 | + :return: |
| 15 | + """ |
| 16 | + # load_dotenv() |
| 17 | + credential = DefaultAzureCredential() |
| 18 | + resource_management_client = ResourceManagementClient(subscription_id=subscription_id, credential=credential) |
| 19 | + tag_filter= f"tagName eq 'Temporary' and tagValue eq 'TRUE'" |
| 20 | + all_rgs_filtered = resource_management_client.resource_groups.list(filter=tag_filter) |
| 21 | + rgs_to_deleted = [] |
| 22 | + for rg in all_rgs_filtered: |
| 23 | + rg_dict = { |
| 24 | + 'name': rg.name, |
| 25 | + 'location': rg.location |
| 26 | + } |
| 27 | + rgs_to_deleted.append(rg_dict) # final dictionary of rgs to be deleted with Temporary tag value as TRUE |
| 28 | + |
| 29 | + print(rgs_to_deleted) |
| 30 | + |
| 31 | + return rgs_to_deleted |
| 32 | +async def delete_resource_groups(subscription_id: str, rgs_to_be_deleted: list[dict]): |
| 33 | + """ |
| 34 | + Delete the resource groups with Temporary tag value as TRUE |
| 35 | + :return: |
| 36 | + """ |
| 37 | + credential = DefaultAzureCredential() |
| 38 | + resource_management_client = ResourceManagementClient(subscription_id=subscription_id, credential=credential) |
| 39 | + |
| 40 | + for rg in rgs_to_be_deleted: |
| 41 | + try: |
| 42 | + print(f"Deleting {rg['name']} from {subscription_id}") |
| 43 | + resource_management_client.resource_groups.begin_delete(resource_group_name=rg['name']).result() |
| 44 | + print(f"Successfully deleted {rg['name']}") |
| 45 | + |
| 46 | + except ResourceNotFoundError: |
| 47 | + |
| 48 | + print(f"Resource group '{rg['name']}' not found.") |
| 49 | + |
| 50 | + except Exception as e: |
| 51 | + |
| 52 | + print(f"Failed to delete resource group '{rg['name']}': {e}") |
| 53 | + # Optional: Add a short delay between deletions to prevent overwhelming the service |
| 54 | + await asyncio.sleep(1) |
| 55 | + |
| 56 | + |
| 57 | +async def main(): |
| 58 | + """To test the code""" |
| 59 | + start_time = datetime.utcnow() # Get start time in UTC |
| 60 | + print(f"Process started at (UTC): {start_time}") |
| 61 | + load_dotenv() |
| 62 | + parser = argparse.ArgumentParser("Decommission nolonger used resource groups in Azure.") |
| 63 | + parser.add_argument("--subscription_name", type=str, required=True,help="Azure subscription name") |
| 64 | + |
| 65 | + args = parser.parse_args() |
| 66 | + |
| 67 | + subscription_name = args.subscription_name |
| 68 | + subscription_id = run_azure_rg_query(subscription_name=subscription_name) |
| 69 | + rgs_to_deleted = await list_resource_groups_with_temporary_tag(subscription_id=subscription_id) |
| 70 | + await delete_resource_groups(subscription_id=subscription_id, rgs_to_be_deleted=rgs_to_deleted) |
| 71 | + end_time = datetime.utcnow() # Get end time in UTC |
| 72 | + print(f"Process completed at (UTC): {end_time}") |
| 73 | + # Calculate and print elapsed time |
| 74 | + elapsed_time = end_time - start_time |
| 75 | + print(f"Total elapsed time: {elapsed_time} (hh:mm:ss)") |
| 76 | + |
| 77 | +if __name__ == "__main__": |
| 78 | + asyncio.run(main()) |
0 commit comments