Trying to apply tags that are set at the resource GROUP level to any resources within the resource group (all resources).
Found a script online and modified it minimally.
It should make sure the tag NAME and tag VALUE are both set based on the resource group (example: if the resource group has tag name "ABCD" and tag value "1234", and a resource underneath the resource group has tag "ABCD" and tag value "4567", then it should overwrite that value with "1234") There is one tag that should be set on all resources. The name we know, but the value we don't.
I've noticed it takes a LONG time to run. A resource group with 10 resources in it might take 1-2 minutes for the script to run against
Any ideas or suggestions?
#List all Resources within the Subscription
$Resources = Get-AzureRmResource
#For each Resource apply the Tag of the Resource Group
Foreach ($resource in $Resources)
{
$Rgname = $resource.Resourcegroupname
$resourceid = $resource.resourceId
$RGTags = (Get-AzureRmResourceGroup -Name $Rgname).Tags
$resourcetags = $resource.Tags
If ($resourcetags -eq $null)
{
Write-Output "---------------------------------------------"
Write-Output "Applying the following Tags to $($resourceid)" $RGTags
Write-Output "---------------------------------------------"
$Settag = Set-AzureRmResource -ResourceId $resourceid -Tag $RGTagS -Force
}
Else
{
$RGTagFinal = @{}
$RGTagFinal = $RGTags
Foreach ($resourcetag in $resourcetags.GetEnumerator())
{
If ($RGTags.Keys -inotcontains $resourcetag.Key)
{
Write-Output "------------------------------------------------"
Write-Output "Keydoesn't exist in RG Tags adding to Hash Table" $resourcetag
Write-Output "------------------------------------------------"
$RGTagFinal.Add($resourcetag.Key,$resourcetag.Value)
}
}
Write-Output "---------------------------------------------"
Write-Output "Applying the following Tags to $($resourceid)" $RGTagFinal
Write-Output "---------------------------------------------"
$Settag = Set-AzureRmResource -ResourceId $resourceid -Tag $RGTagFinal -Force
}
}
A few things the script should do too, which i'm not sure this script does.
- If the resource already has 15 tags, it will not overwrite a tag with the resource group level tag; it will just skip it
- Rather than copying ALL tags from the resource group to the resource, there's only one tag. Could we put logic in where if the resource group has a tag of "ABCDEFG" for instance, it will copy it over? Any other tags it won't?
- Perhaps to speed it up, is it possible to just CHECK if the tag name and value on the resource level matches the tag on the resource group level, and not to overwrite it if it already matches. I suspect it's the write that is taking time, and just reading the tags isn't.