Search code examples
azurepowershellcsvtagsazure-functions

Adding tags to azure VMs via CSV


trying to add tags to VMs via CSV data, right now I have the below code:

if ($context.Account -eq $null) {
#    Login-AzureAccount
    Connect-AzAccount
}

# Select Azure Subscription

$subscriptionId = (Get-AzSubscription | Out-GridView -Title "Select an Azure Subscription ..." -PassThru).SubscriptionId

#Select specified subscription ID

Select-AzSubscription -SubscriptionId $subscriptionId

$InputCSVFilePath = "test.csv"
$csvItems = Import-Csv $InputCSVFilePath

################


foreach ($item in $csvItems){
    Clear-Variable r
    
    #$r = Get-AzResource -ResourceGroupName $item.ResourceGroup -Name $item.VM -ErrorAction Continue
    $r = Get-AzResource -Name $item.VM
    ################ 

    if ($r -ne $null){

        if ($r.Tags){
            # Tag - Client DL

            if ($r.Tags.ContainsKey("Client_DL")){          
                $r.Tags["Client_DL"] = $item.ClientDL
                
            }else{
                $r.Tags.Add("Client_DL", $item.ClientDL)
                
            }

            # Tag - Priority

            if ($r.Tags.ContainsKey("Priority")){               
                $r.Tags["Priority"] = $item.Priority
                
            }else{
                $r.Tags.Add("Priority", $item.Priority)
            }
        }
    }else{
        Write-Host "No VM found named $($item.VMName)!"
    }
}

I verified that my code does indeed go through the functions but for some reason the tags are not being set on my VM's. I ran the commands manually in powershell and I was able to set a tag by doing:

$r = Get-AzResource -Name TestVM
$r.Tags.Add("Client_DL", "TEST-DL") 

Am I missing something? i'm running a Set-PSDebug -Trace 2 when running my code and it seems to check out just fine, but the tags aren't getting set/written.


Solution

  • So you're adding the tags in memory but you're not calling any of the Az cmdlets to set the tags back on the resource.

    You can see in the example in the docs here they return the VM with Get-AzResource, append their new tag to the existing tags and then use Set-AzResource to write the newly added tag back.

    Just be careful of that

    When updating tags through PowerShell, tags are updated as a whole. If you are adding one tag to a resource that already has tags, you will need to include all the tags that you want to be placed on the resource

    Alternatively you could use Update-AzTag which has an -Operation parameter and lets you choose whether you want to merge, replace or delete the existing tags.

    https://learn.microsoft.com/en-us/powershell/module/az.resources/update-aztag?view=azps-6.0.0

    Ultimately you'd need to set back your $r.Tags value to your resource as the last operation within your if statement.