Azure resource tagging is a great way to label or group your Azure resources based on custom names and values. For example you could have a tag named “owner” for specifying the resource owner or “patchphase” for noting what phase to patch the OS or application running on a virtual machine.
The issue with Azure resource tagging is the management of the tags when you have more than a handful of resources, so pretty much every Azure subscription ?
Thankfully you can use the PowerShell Az module or indeed the Azure CLI to manage your resource tagging in bulk. This post concentrates on using the PowerShell Az module. If you don’t have the PowerShell Az module already installed then you can follow this Microsoft document: Install Azure PowerShell
The first job is to connect or login to your Azure account. If you have access to multiple subscriptions you also need to set which subscription to work with. Use the commands below to login and set your subscription scope for the session:
Connect-AzAccount Get-AzSubscription Set-AzContext -Subscription "subscriptionId"
Once connected you can press on with managing your resource tagging. To start try running Get-AzResource to return all resources in the subscription. You can filter the returned results by passing various parameters (see link to documentation) e.g. Get-AzResource -ResourceType "Microsoft.Compute/virtualMachines"
will return all virtual machine resources in the subscription.
Once you know which resources you want to manage it’s just a case of assigning them into a variable e.g. $resources = Get-AzResource -ResourceType "Microsoft.Compute/virtualMachines"
so you can manipulate them.
Next load the variable and use a ForEach loop to either add or remove tags as required:
$resources | ForEach-Object { $_.Tags.Add("tagName", "tagValue") } $resources | ForEach-Object { $_.Tags.Remove("tagName") }
Now the resources in the variable have been manipulated they need to actually be updated in Azure. To do that run: $resources | Set-AzResource -Force
I am getting below error, could you please help.
PS C:\Users\> $resources | ForEach-Object { $_.Tags.Add(“ENV”, “POC”) }
You cannot call a method on a null-valued expression.
At line:1 char:31
+ $resources | ForEach-Object { $_.Tags.Add(“ENV”, “POC”) }
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At line:1 char:31
+ $resources | ForEach-Object { $_.Tags.Add(“ENV”, “POC”) }