Search code examples
azureazure-devopsazure-resource-managerazure-cli

How to Tag Azure resources seamlessly with different tags


First we used Terraform to create our resources along with proper tagging. But later we identified that the Admin team performed some manual modifications to the resource as part of some issues quick fixes and all. At the end the terraform state file of these resources are out of sync.

Now we have requirement to update the tags of the already provisioned resources (terraform used) with new additional tags to them. When we tried by adding the terraform manifests with the changes for the tagging, and executed terraform plan, and could see that some resources are showing to replace and we are not advised to perform that .

We tried to manually import the changes what performed manually from portal, to the terraform state so that we can apply the tag changes from the terraform itself. But we are facing concerns like cant update the resources in minute level from the portal to the state file?

is there any automated way to tag a list of azure resources as per the tags specified for each resources. and we can update the state file so easily ?


Solution

  • On way that would work is using Azure PowerShell's Update-AzTag to update or add new tags to already existing resources in your subscription. I have few resources that are tagged as Key1:Value1 in my tenant where I'm trying to change them to SampleKey:SampleValue. Below is the script that worked for me to update all the tags that are in my tenant.

    $SubscriptionId = Get-AzSubscription -TenantId (Get-AzContext).Tenant
    $replacedTags = @{"key1"="value1"; "SampleKey"="SampleValue";}
    foreach($SubId in $SubscriptionId) {
        $ResourceId = "/subscriptions/"+$SubId.Id
        Update-AzTag -ResourceId $ResourceId -Tag $replacedTags -Operation Replace
    }
    

    RESULTS

    enter image description here