How to import the tags in Azure?


In the previous article, we have seen that we can export the Azure resource tags in the JSON file or CSV format. There are some cases when you rebuild your resource and you might need to restore your tags or someone with the authorized person to have azure resource access and he accidentally deletes the tags and we need to restore them. In such cases, if we have the tags backup already we can import them to the resources.

In the below example, we suppose we have the Azure VM tags backup stored in the CSV file format and after rebuilding it we need to add tags again or consider the other scenario that we need to copy the existing VM tags to the newly built VM.

We have an existing azure VM TestVM and we will export its tags first to the Tags.csv file with the below commands.

Get-AzVM -VMName TestVM | Select -ExpandProperty Tags | ConvertTo-Json | ConvertFrom-Json | Export-Csv C:\Temp\Tags.csv -NoTypeInformation

We have once the tags are stored in a CSV file we can import them.

PS C:\> Import-Csv C:\Temp\tags.csv
For    Patching_Day    Application    Owner
--- ------------ ----------- -----
Ansible Sunday       SecretTag    Chirag

We need to apply the above tags to the new VM TestMachine2k16. So we will use the below commands.

$tags = Import-Csv C:\temp\Tags.csv
$vm = Get-AzVM -VMName TestMachine2k16
foreach($head in $tags.psobject.Properties.Name){
   $newtag = @{$head = $tags.$head}
   Update-AzTag -ResourceID $vm.id -Tag $newtag -Operation Merge -Verbose
}

Updated on: 06-Apr-2021

370 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements