Today I’m doing an Azure Migration and consolidation for a client and they wanted to tag everything within the existing Resource Group where is it deployed before we started moving things around to other Resource Groups and Subscriptions. Two important notes: first they didn’t mind if the RG has current TAGs, if it does then they can be added to the resources within that RG and they didn’t want to lose any of the existing TAGs on the resources.
So, first I tagged all of the Resource Groups with this tag:
KEY: OrginialRGName / Value: [NAME OF RESOURCE GROUP]
Next, I used the following script to load all the resource groups into an array, read the currently assigned tag values on the resource group and the resources. Finally, it will apply all the tags onto the resources which will now include the OriginalRGName tag and value. This will be done to all resources in the subscription.
groups=$(az group list --query [].name --output tsv)
for rg in $groups
do
jsontag=$(az group show -n $rg --query tags) || true
t=$(echo $jsontag | tr -d '"{},' | sed 's/: /=/g') || true
r=$(az resource list -g $rg --query [].id --output tsv) || true
for resid in $r
do
jsonrtag=$(az resource show --id $resid --query tags) || true
rt=$(echo $jsonrtag | tr -d '"{},' | sed 's/: /=/g') || true
az resource tag --tags $t$rt --id $resid || true
done
done
Notice how the Tags on the resource remained and my new tag, OriginalRGName is now put in place!
You might get some errors on resources that don’t show in the portal or support tags, like alerts for Azure montior, but these can be ignored. Give it a try on a test subscription and have fun TAGing!
Thanks for that. I also wrote a blog about tagging existing Resource Groups and items contained with a set of tags using PowerShell you might useful.
https://blog.nicholasrogoff.com/2018/11/01/resource-tag-management-in-microsoft-azure/
Nice post. I have a slightly different version that uses jq to merge the two sets of tags, nicely handling any duplicates, and it also deals with any keys or values that have spaces:
#!/bin/bash
for rg in $(az group list –query [].name –output tsv)
do
rgTags=$(az group show -n $rg –query tags –output json)
for resId in $(az resource list -g $rg –query [].id –output tsv)
do
resTags=$(az resource show -g $rg –ids $resId –query tags –output json)
tags=$(echo “[$rgTags,$resTags]” | jq ‘.[0] * .[1]’ | tr -d “{},” | tr ‘\n’ ‘ ‘ | sed ‘s/”: “/=/g’)
echo “$resId:”
eval az resource tag –id $resId –tags $tags –query tags –output jsonc
done
done
That’s awesome!