0
votes

I am trying to delete the resource groups and resources in it using python code. I have tried this in powershell and it works perfect. Now my organization wanted in Python. I am really new to python and trying to write the code and failed .

Here is the powershell code for the same. Can anyone help on getting the code in python.

Thanks in advance.

 $rgs = Get-AzureRmResourceGroup; 

# $rgs=Get-AzureRmResourceGroup -name "TestResourceGroupToClean1";

if(!$rgs)
{ 
    Write-Output "No resource groups in your subscription"; 
} 
else{


    Write-Output "You have $($(Get-AzureRmResourceGroup).Count) resource groups in your subscription"; 
    foreach($resourceGroup in $rgs)
    { 
        $name=  $resourceGroup.ResourceGroupName; 
     if($resourceGroup.Tags.ExpiryDate)
     {
    try{
         $ResourceGroupTagDate=[datetime]::ParseExact($resourceGroup.Tags.ExpiryDate,'MM/dd/yyyy',$null)
         $count = (Get-AzureRmResource | where { $_.ResourceGroupName -match $name }).Count;
            if($ResourceGroupTagDate.Date -lt $today.Date)
            { 
                $subject="Automated Mail from Resource Group Cleaner"
                $body="Resource Group $($resourceGroup.ResourceGroupName) including resources has been deleted"
                Write-Output "The resource group $name has $count resources. Deleting it..."; 
                Remove-AzureRmResourceGroup -Name $resourceGroup.ResourceGroupName -Force; 
                Write-Output "The resource group $name and $count resources. Deleted..";
                Send-MailMessage -To '[email protected]' -Subject $subject -Body $body -UseSsl  -Port 587 -SmtpServer 'smtp.office365.com' -From $userid -Credential $creds 
            }

            }
2

2 Answers

1
votes

Here is the Error I am getting ############################# Failed Traceback (most recent call last): File "C:\Temp\kukzwo13.tgf\9bd12580-5780-4109-abab-66e88fb4df87", line 59, in if not item.tags['ExpiryDate']:KeyError: 'ExpiryDate'

In python code, we need to check the key is valid for the dictionary. I have done a demo for deleting the resource group by tags with python code.

from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.resource import ResourceManagementClient
import datetime
from datetime import time

# Tenant ID for your Azure Subscription
TENANT_ID = 'tenant id '
# Your Service Principal App ID
CLIENT = 'client id'
# Your Service Principal Password
KEY = 'scret key'
subscription_id = 'subscrptionId'
credentials = ServicePrincipalCredentials(client_id=CLIENT, secret=KEY, tenant=TENANT_ID)
client = ResourceManagementClient(credentials, subscription_id)
groups = client.resource_groups.list()
null_variable = None
for item in groups:
    if item.tags != null_variable:
            if 'ExpiryDate' in item.tags:
                expiryDate = datetime.datetime.strptime(item.tags["ExpiryDate"],"%m/%d/%Y")
                timediff = expiryDate < datetime.datetime.today()
                if timediff:
                    print(item.tags["ExpiryDate"])
                    print(item.name)
                    client.resource_groups.delete(item.name)