Microsoft Azure - Removing Unused Services From Azure - GeeksforGeeks

21 Sep, 2021
In this article, we will learn how to keep your Azure subscription clean. Most teams that work in an Azure subscription forget to delete unused resources. This makes it difficult to see which resources are still being used and it makes you pay for resources that you don’t use. 
Here, for instance, we have an Azure storage account that we don’t use. Let’s clean that up with a script. Given below is a PowerShell script. It cleans up unused resources. 
$connectionName="AzureRunAsConnection"

try
{
    # Get the connection "AzureRunAsConnection "
    $servicePrincipalConnection=Get-Automation Connection -Name $connectionName

    Connect-AzAccount
        -ServicePrincipal
        -Tenant $servicePrincipalConnection. Tenant Id
        -Applicationid Sservice PrincipalConnection. ApplicationId
        -CertificateThumbprint Sservice Principal Connection.CertificateThumbprint
}

catch{
    if (!$servicePrincipalConnection);
    {
        $ErrorMessage = "Connection SconnectionName not found."
        throw $ErrorMessage

    } else{

        Write-Error Message $_.Exception 
        throw $_.Exception
        }
}

$expResources Search-AzGraph -Query 'where todatetime(tags.expireOn)< now()| project id'

foreach ($r in $expResources) {
    Remove-AzResource ResourceId $r-id-Force
}

$rgs Get-AzResourceGroup;

foreach($resourceGroup in $rgs) {
    $names SresourceGroup. ResourceGroupName; 
    $count (Get-AzResource | Where-Object: $_.ResourceGroupName -match $name }). Count;

$rgs = Get-AzResourceGroup;

foreach($resourceGroup in $rgs) {
    $names = $resourceGroup.ResourceGroupName;
    $count = (Get-AzResource | Where-Object( $_.ResourceGroupName -match $name )).Count;
if ($count -eq 0){ 
    Remove-AzResourceGroup -Name $name -Force
    }
}
The first thing the script does is log in to Azure using a service principle. 
$connectionName="AzureRunAsConnection"

try
{
    # Get the connection "AzureRunAsConnection "
    $servicePrincipalConnection=Get-Automation Connection -Name $connectionName

    Connect-AzAccount
        -ServicePrincipal
        -Tenant $servicePrincipalConnection. Tenant Id
        -Applicationid Sservice PrincipalConnection. ApplicationId
        -CertificateThumbprint Sservice Principal Connection.CertificateThumbprint
}

catch{
    if (!$servicePrincipalConnection);
    {
        $ErrorMessage = "Connection SconnectionName not found."
        throw $ErrorMessage

    } else{

        Write-Error Message $_.Exception 
        throw $_.Exception
        }
}
 Next, we used the Azure Resource graph to get the resources that should be cleaned up. Unfortunately, there’s no easy way to determine which resources should be removed, so we need users to create a tag for those resources. A tag called expireOn with a value of the date when it should expire. Here, we get all resources with a date that is earlier than today. 
$expResources Search-AzGraph -Query 'where todatetime(tags.expireOn)< now()| project id'
The script loops over the resources and removes them.
foreach ($r in $expResources) {
    Remove-AzResource ResourceId $r-id-Force
}
Finally, because the Azure Resource graph doesn’t return resource groups, we get all of those and iterate over them, and when a resource group is empty, it gets deleted. 
$rgs Get-AzResourceGroup;

foreach($resourceGroup in $rgs) {
    $names SresourceGroup. ResourceGroupName; 
    $count (Get-AzResource | Where-Object: $_.ResourceGroupName -match $name }). Count;

$rgs = Get-AzResourceGroup;

foreach($resourceGroup in $rgs) {
    $names = $resourceGroup.ResourceGroupName;
    $count = (Get-AzResource | Where-Object( $_.ResourceGroupName -match $name )).Count;
if ($count -eq 0){ 
    Remove-AzResourceGroup -Name $name -Force
    }
}
Tagging resources is easy. You can do it in the portal with the Azure CLI or in an Azure Resource Manager template. Here, we can add a tag to the storage account, expireOn and the date should have to format year, month, day. That’s it.
To automate the process, we’ll run the script with Azure Automation. First, we’ll give it a name, and next, we’ll select a Resource group. This creates the service principle that the script uses to log into Azure. 
Here is the Azure Automation account. The scripts uses PowerShell modules that aren’t installed by default. So we have to install them first.  For this click on “Browse Gallery” and we can pick them from here. 
First, we need AZ Account and we need to import them. 
Next, search for the AZ Resource graph that we use to query the resource graph and import it. 
And finally, search for AZ Resources and import it as well. 
Now, we’ll create a Runbook. This is the mechanism that we use to run the PowerShell script in Azure. First, give it a name and select PowerShell for the runbook type and create.
 Now, paste in the script and save the runbook and publish it so that we can use it.
To make it run automatically, we’ll add a schedule to it.  We need to give the schedule a name. Now, select a start date and time. 
This will run the script every day. So now, when we look at our Resource group, the storage account is removed. The script worked. It is important to remove unused Azure resources to keep your costs in check and your Azure subscription clear. You can do it with a script and automate it with Azure Automation.
Blogathon-2021
Cloud-Computing
Picked
Blogathon
Microsoft Azure
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Import JSON Data into SQL Server?
How to Install Tkinter in Windows?
SQL - Multiple Column Ordering
How to pass data into table from a form using React Components
How to Create a Table With Multiple Foreign Keys in SQL?
Microsoft Azure - Get CPU Utilization Data of a Azure VM in Azure Portal
Microsoft Azure - Installation of Service Bus Explorer
Microsoft Azure - Using C# in CosmoDB
Microsoft Azure - Tracking Memory Utilization of Azure VM using KQL Log Query
Microsoft Azure - Track CPU Utilization of a Azure Virtual Machines using KQL Log Query