PowerShell script to update Azure resource tags

Veeresh Kumar
3 min readSep 25, 2021

I have come across situation where azure cloud resources deployed are not having the proper tags. Going to Azure portal, updating tags on each resources would be tedious job and if, you are having larger infrastructure it would take months update it. I needed an automated way to find the resources based on pattern and update the tags accordingly.

Well, Azure PowerShell has all the capability to achieve the task.

Here we go …!!!

Prerequisites:

  • PowerShell 5.1 or later
  • Service Principal Name and Secret to login to Azure
  • SPN should have Administrator or Owner or Contributor privileges to update resource tags.
  • Azure Subscription Id
  • Azure Tenant Id
  • Az.Module ≥ 6.4.0

Note: In this approach, have used SPN login credentials.

Follow the below steps to Update/Replace/Delete tags on resources based on pattern:

  1. Copy and Paste the below script on to your system, Save the file as Az_UpdateResourceTags.ps1

2. Go to the File path and Run the script as shown in the below by passing the relevant input parameters:

Merge: This Updates/Appends tags to the existing tags.

Az_UpdateResourceTags.ps1 -pattern ‘chef*’ -subscriptionId <subscription_id> -spnId ‘<application_id>’ -spnSecret ‘<secret>’ -tenantId ‘<tenantId>’ -tags @{“Creator”=”VKN”; “Updater”=”PowerShell”} -action ‘Merge’

Replace: This overwrites existing tags with new tag values passed.

Az_UpdateResourceTags.ps1 -pattern ‘chef*’ -subscriptionId <subscription_id> -spnId ‘<application_id>’ -spnSecret ‘<secret>’ -tenantId ‘<tenantId>’ -tags @{“Creator”=”VKN”; “Updater”=”PowerShell”} -action ‘Replace’

Delete: This deletes the tags on resource based on the input tags passed.

Az_UpdateResourceTags.ps1 -pattern ‘chef*’ -subscriptionId <subscription_id> -spnId ‘<application_id>’ -spnSecret ‘<secret>’ -tenantId ‘<tenantId>’ -tags @{“Creator”=”VKN”; “Updater”=”PowerShell”} -action ‘Delete’

3. Post running the above command you will see the below output based on the action parameter and go to the respective resource on portal and verify:

Merge: tags merged resources output

Verify the Tags from portal:

Replace: tags replaced resources output

Verify from the portal:

Delete: tags deleted resources output

Verify from portal:

Note: I am showing only one resource from portal. This script updates all the matched resources, if you observe the above script outputs.

Hope this helps ..!! Happy scripting ..!!

--

--

Veeresh Kumar

He is a Sr. DevOps Engineer loves to automate cloud infrastructure and App deployments. #Terraform #Azure #Jenkins #Ansible #Chef #Bash #PowerShell #AWS #GCP