Vowneee
Vowneee

Reputation: 1459

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 ?

Upvotes: 0

Views: 996

Answers (2)

Dou Xu-MSFT
Dou Xu-MSFT

Reputation: 3221

@SwethaKandikonda has given the script that can be used in Azure CLI. On the base of his answer, i want to make additional information. If you want to automate this using azuredevops pipeline, here is a YAML pipeline example:

# Starter pipeline

trigger:
- master

pool:
  vmImage: ubuntu-latest
steps:
- task: AzureCLI@2
  inputs:
    azureSubscription: 'your subscription'
    scriptType: 'pscore'
    scriptLocation: 'inlineScript'
    inlineScript: 'az tag update --resource-id /subscriptions/{ sub-id }/resourceGroups/{ rg }/providers/Microsoft.Storage/storageAccounts/{your saName} --operation replace --tags key1=value1 key3=value3'

Running result

yaml pipeline result

It will automatically tag the resource after running the pipeline successfully.

Upvotes: 1

SwethaKandikonda
SwethaKandikonda

Reputation: 8234

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

Upvotes: 1

Related Questions