Recently, I had to go back and correctly tag a whole bunch of items in a new resource group, none of which had been given tags.
This kind of task can be daunting in the Azure portal… you have to click each, click the tags tab, and then type each key/value, for each tag, and save. So… tagging 50 resources with 5 tags each ends up being 50 * 2 * 5 + 50 = 550 clicks at minimum, plus all the typing! Clearly, this is a task better suited for the CLI.
Using the Azure CLI
Microsoft actually has a very full featured tutorial on this subject right here. The more advanced code they provide will actually find every resource you have in every group and give each resource the tags from the group. It will even optionally retain existing tags for resources that are already tagged.
I wanted something a little simpler with the login included so that I can quickly copy it in to fix a resource group here and there without worrying about affecting all the other resource groups. So, here is the code. It also counts the items so you can see progress as it can take some time.
Note, I wanted to forcibly replace all the tags on the resources with the RG tags as some of them were incorrect. You can get code to merge with existing tags from the link noted above if you prefer.
tenant="your-tenant-id"
subscription="your-subscription-name"
rg="your-resource-group-name"
# Login to azure - it will give you a message and code to log in via
# a web browser on any device
az login --tenant "${tenant}" --subscription "${subscription}"
# Show subscriptions just to show that we're on the correct one.
echo "Listing subscriptions:"
az account list --output table
# Get the tags from the resource group in a useful format.
jsontag=$(az group show -n $rg --query tags)
t=$(echo $jsontag | tr -d '"{},' | sed 's/: /=/g')
# Get all resources in the target resource group, and loop through
# them applying the tags from the resource group. Count them to show
# progress as this can take time.
i=0
r=$(az resource list -g $rg --query [].id --output tsv)
for resid in $r
do
az resource tag --tags $t --id $resid
let "i+=1"
echo $i
done
Also note that you can find the total number of resources you are targeting in advance with this command so the counter is more practical :).
az resource list --resource-group "your-rg-name" --query "[].name" | jq length