How to apply tags to all resources in your subscription
Tags are a useful way to keep track of who owns what resource in a company wide Azure subscription.
You can enforce the creation of tags via the Apply tag and its default value policy you can assign to all or part of your subscription. But this only works for future resource created. What if you already have a lot there?

Set tags at the resource groups

We can create the tags we need at the resource group level with this:
1
Get-AzureRmResourceGroup | ForEach-Object { Set-AzureRmResourceGroup -Name $_.ResourceGroupName -Tag @{ Key="value" } }
Copied!
This will set the tag for all resource groups.

Set tags for the resources within the groups

Then to copy the tags at the resource groups and assign them to the resources within the groups you can run the following:
1
$groups = Get-AzureRmResourceGroup
2
3
foreach ($group in $groups)
4
{
5
$resources = $group | Find-AzureRmResource
6
Write-Host "Processing resource group $($group.ResourceGroupName)" -f Cyan
7
8
foreach ($r in $resources)
9
{
10
$resourcetags = (Get-AzureRmResource -ResourceId $r.ResourceId).Tags
11
12
foreach ($key in $group.Tags.Keys)
13
{
14
if (($resourcetags) -AND ($resourcetags.ContainsKey($key))) { $resourcetags.Remove($key) }
15
}
16
$resourcetags += $group.Tags
17
Set-AzureRmResource -Tag $resourcetags -ResourceId $r.ResourceId -Force
18
}
19
Write-Host
20
}
Copied!

Further reading

Last modified 2yr ago