|
########################################################################################## |
|
###################### To be used with an Azure Automation runbook |
|
###################### make sure you create the Automation Credential -Name 'AzureRunAsConnection' |
|
###################### make sure you Automation Variable -Name 'SubscriptionID' |
|
###################### |
|
########################################################################################## |
|
# Thanks to https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-using-tags |
|
|
|
$ServicePrincipalConnection = Get-AutomationConnection -Name 'AzureRunAsConnection' |
|
|
|
$null = Add-AzureRmAccount ` |
|
-ServicePrincipal ` |
|
-TenantId $ServicePrincipalConnection.TenantId ` |
|
-ApplicationId $ServicePrincipalConnection.ApplicationId ` |
|
-CertificateThumbprint $ServicePrincipalConnection.CertificateThumbprint |
|
|
|
Get-AzureRmSubscription -SubscriptionId (Get-AutomationVariable -Name 'SubscriptionID') | Select-AzureRmSubscription |
|
|
|
########################################################################################## |
|
###################### apply all tags from a resource group to its resources |
|
###################### and retain existing tags on resources that are not duplicates |
|
###################### and not overwrite any duplicate tags |
|
###################### |
|
########################################################################################## |
|
|
|
# Get all Resource Groups |
|
$ResourceGroups = Get-AzureRmResourceGroup |
|
foreach ($Group in $ResourceGroups) { |
|
$group = Get-AzureRmResourceGroup -Name $Group.ResourceGroupName |
|
if ($null -ne $group.Tags) { |
|
$resources = Get-AzureRmResource -ResourceGroupName $group.ResourceGroupName |
|
foreach ($r in $resources) { |
|
$resourcetags = (Get-AzureRmResource -ResourceId $r.ResourceId).Tags |
|
if ($resourcetags) { |
|
foreach ($key in $group.Tags.Keys) { |
|
if (-not($resourcetags.ContainsKey($key))) { |
|
$resourcetags.Add($key, $group.Tags[$key]) |
|
} |
|
} |
|
Set-AzureRmResource -Tag $resourcetags -ResourceId $r.ResourceId -Force |
|
} |
|
else { |
|
Set-AzureRmResource -Tag $group.Tags -ResourceId $r.ResourceId -Force |
|
} |
|
} |
|
} |
|
} |