How to reuse existing authentication to Azure from powershell.
When coding Azure it is common to perform Connect-AzAccount to call for login prompt before running all other Azure cmedlets. It will show you login prompt even if session of your powershell console is already authenticated, what is annoying. Especially if you debugging your program and need to run it many times. I am using following code to avoid this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
$subscriptionID = "" #put your subscription id here $tenantID = "" #put your tenant id here #Start of logging into azure block $currentAZContext = Get-AzContext if ($currentAZContext.Tenant.id -ne $tenantID){ write-host "This script is not authenticated to needed tenant. Runnng authentication" Connect-AzAccount -TenantId $tenantID -SubscriptionId $subscriptionID } else{ write-host "This script is already authenticated to needed tenant - reusing authentication." } Set-AzContext -subscriptionId $subscriptionID -Tenant $tenantID if (! $?){ write-host "Error occured during Set-AzContext. Error message: $($error[0].Exception.InnerException.Message)" write-host "trying to discconect and reconnect" Disconnect-AzAccount Connect-AzAccount -TenantId $tenantID -SubscriptionId $subscriptionID Set-AzContext -subscriptionId $subscriptionID -Tenant $tenantID } #End of logging into azure block #after authentication perform some simple vm inventory for example: $VMs = Get-AzVM write-host "Number of VMs: $($VMs.count)" foreach($currVM in $VMs){ Write-host "VM name: $($currVM.name)" Write-host " Resource group: $($currVM.ResourceGroupName)" Write-host " VM ID: $($currVM.VmId)" Write-host " VM size: $($currVM.HardwareProfile.VmSize)" write-host } |
Before running you need to fill in your subscription and tenant IDs. The authentication block is between
#Start of logging into azure block
#End of logging into azure block
comments.
It will authenticate you, first checking your current Get-AZContext. If you have good status (already authenticated to required tenant and subscription) – it will perform Set-AzContext to select required subscription as target of your following cmdlets. It will call Connect-AzAccount (the one which opens login prompt) only in case you not already authenticated.
Then small example block of code collecting current subscription’s VMs statuses is added.