Open In App

Microsoft Azure – Removing Unused Services From Azure

Improve
Improve
Like Article
Like
Save
Share
Report

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.

Conclusion:

As seen above Azure environment grows and evolves, and we may find that you have unused or underutilized resources that are consuming unnecessary costs. Removing unused services from Azure can help you optimize your costs, simplify your environment, and reduce your attack surface. Here are some steps you can take to remove unused services from Azure:

  1. Identify unused services: The first step is to identify which services are not being used or is underutilized. You can use Azure Cost Management + Billing to analyze your usage and identify services that are not being used or are not providing sufficient value.
  2. Evaluate dependencies: Before removing a service, evaluate any dependencies it may have. Some services may be required by other services or applications, and removing them may cause issues. Make sure to understand the dependencies before removing a service.
  3. Remove unused services: Once you have identified unused services and evaluated any dependencies, you can remove them from Azure. You can use the Azure portal, Azure PowerShell, or Azure CLI to remove services. Make sure to follow the recommended procedure for each service to avoid any unintended consequences.
  4. Clean up resources: After removing the service, you should clean up any associated resources, such as storage accounts or virtual networks. These resources may still be consuming costs even if the service is no longer in use.
  5. Monitor usage: Finally, it’s important to monitor your Azure environment regularly to ensure that new services are not being created unnecessarily or that services are not being overprovisioned. Azure Cost Management + Billing can help you monitor your usage and identify potential areas for optimization.

By following these steps, you can effectively remove unused services from Azure and optimize your costs while maintaining a secure and streamlined environment.


Last Updated : 18 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads