Instantly share code, notes, and snippets.
Last active
December 4, 2018 01:38
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
########################################################################################## | |
###################### 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 | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment