Posted on Leave a comment

Find resource groups that contain tags on Azure using az cli

Sometimes you may need to massively search for resource groups or resources on Azure that have tags set. For example you may have some tags like temp resource that you want to delete with cron jobs. I myself wanted such a script and the first thing to do was to ask chatGPT about this. Although the provided answer is a good starting point I wanted a version that will bring all the resources that have a tag, and not a specific tag. I was searching for tags in general and not for a specific tag.

For such case I created my own script using az cli. In order to use it you will need to first login inside azure with your credentials.

az login

and then set your subscription

az account set --subscription "ID"

The script which brings resource-groups with tags can be found below.

$rgroups = az group list | ConvertFrom-Json
Write-Host Total Resource groups: $rgroups.Count  

$tags = @()
foreach ($item in $rgroups)
{
 if ( -not [string]::IsNullOrEmpty($item.tags)  ) { $tags+= $item } 
}
Write-Host Resource groups with Tags: $tags.Count  

echo $tags

When you run the script you can get the total number of resource groups and the ones that contain tags. You can then use the tags object to loop through the items with tags.

You can use the same logic to find also resources with tags inside an azure subscription

$resources = az resource list | ConvertFrom-Json
Write-Host Total Resources: $resources.Count  

$tags = @()
foreach ($item in $resources)
{
 if ( -not [string]::IsNullOrEmpty($item.tags)  ) { $tags+= $item } 
}
Write-Host Resources with Tags: $tags.Count  

echo $tags

Youtube video: