Search code examples
azurepowershellazure-powershellazure-ad-graph-api

Query resources in resource groups where tags are missing


I have got Azure resources within specific resource groups, however I do need to ensure that all resources have the following tags.

  • Environment

  • Cost_centre

  • Department

  • Owner

  • Type

So far it has been a manual process of checking each resources, but I think the work is now complete but was wondering if there is a way tow rite a powershell script or a Azure graph query to check that all resources within the specific resource group have the following tags, and if not highlight the resources that are missing any of the tags highlighted above.

What has been confusing for me is that each resource group has a mixture of resource types i.e App services, SQL, storage accounts etc. How do I capture all resource types to check that the tags are in place and only highlight resources that are missing any of the tags above.

Thanks in advance.


Solution

  • Query resources in resource groups where tags are missing

    You can use below PowerShell script and I followed Document1 and Document2:

    In my case given two resource groups , you can also get all resource groups using $rgs = Get-AzResourceGroup and taken only one tag(hello) for example:

    $rgs = @("rithpyser", "rithtest_group")  
    $ith_needed_tags = @("hello")
    foreach ($r in $rgs) {
        $all_res = Get-AzResource -ResourceGroupName $r
        foreach ($rith_res in $all_res) {
            $rgt = $rith_res.Tags.Keys
            $mt = $ith_needed_tags | Where-Object { $_ -notin $rgt }
            if ($mt.Count -gt 0) {
                Write-Output "Hello Rithwik, Resource: $($rith_res.Name) in Resourec group : $r is missing tags: $($mt -join ', ')"
            }
        }
    }
    

    Output:

    enter image description here