Read Tags from Azure Resource Groups and track using Table Storage

Published on
Reading time
Authors

If you run in an environment where you need to track changes to Tags on Resource Groups in Azure then you may find this PowerShell snippet useful as code to drop into a Runbook.

The snippet will enumerate all Resource Groups in a Subscription (we assume you are already logged into the Subscription you want to use) and then extract all Tags from each Resource Group and write the details to Azure Table Storage.

record-tags-in-storage-table.ps1
Import-Module AzureRmStorageTable

$runDateTime = Get-Date -Format "yyyy-MM-ddTHH\:mm\:ss.fffffffzzz"
$resourceGroup = "STORAGE_RESOURCE_GROUP"
$storageAccount = "STORAGE_ACCOUNT_FOR_TABLE"
$tableName = "STORAGE_ACCOUNT_TABLE_NAME"

# Connect to Storage Account (we assume you have already connected to a Subscription using Login-AzureRmAccount)
$saContext = (Get-AzureRmStorageAccount -ResourceGroupName $resourceGroup -Name $storageAccount).Context
$table = Get-AzureStorageTable -Name $tableName -Context $saContext

# Read all Resource Groups in current subscription
$rgs = Get-AzureRmResourceGroup

ForEach ($rg in $rgs) {

    # Partition Key
    # Strip leading character (/) and then replace remaining / with - as / illegal in partiton key
    $partitionKey = $rg.ResourceId.Substring(1).Replace("/","-");

    # Read all tags on the Resource Group
    $tags = $rg.Tags;

    # Tag entries
    if ($tags -ne $null)
    {
        ForEach($tag in $tags.GetEnumerator())
        {
            $rowKey = $tag.Key + "-" + $runDateTime;

            # Could inline this hashtable, but this makes it clear what we are recording
            $trackValues = @{}
            $trackValues.Add("ResoureGroupName",$rg.ResourceGroupName);
            $trackValues.Add("TagName",$tag.Key);
            $trackValues.Add("TagValue",$tag.Value);

            # Write new row to Table Storage. Property will be expanded to columns in table
            Add-StorageTableRow -table $table -partitionKey $partitionKey -rowKey $rowKey -property $trackValues
        }
    }
}

Once you run this snippet you will be able to use the data for reporting purposes, where each Resource Group's Resource ID will be used as the Partition Key, with the Tag Name (Key) and the current Date / Time used as a Row Key. You now have a reporting source you can use in the likes of Power BI.

description

Happy Days 😎