Reusable authentication to Azure

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:

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.

Leave a Reply

Your email address will not be published.