Skip to content

Instantly share code, notes, and snippets.

@marckean
Last active December 4, 2018 01:38
Show Gist options
  • Save marckean/5af82a7eb007bdd6f7008986a536c4d7 to your computer and use it in GitHub Desktop.
Save marckean/5af82a7eb007bdd6f7008986a536c4d7 to your computer and use it in GitHub Desktop.
##########################################################################################
###################### 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