Creating temporary Azure CLI login sessions

Share on:

The Azure CLI is my preferred way of working with Azure from the command line - I love the discoverability of the commands. az --help is always a great reminder of the root commands and I can keep applying --help as I work my down the various levels - it’s much easier to remember than all the various Az PowerShell commands.

You always start with an az login to sign into Azure, but there may be times you need to temporarily connect as another account to the same subscription. If you use az login again, you’re effectively signing out the previous account and there’s no way to switch back to the original account without going through another az login.

I ran into this issue recently because I needed to temporarily sign in as an Azure service principal to perform an action, and then silently switch back to the original user’s context.

The Azure CLI allows you to control where its configuration folder is stored using the AZURE_CONFIG_DIR environment variable. Using this knowledge I came up with this:

 1try {
 2    # Temporarily point the Azure CLI's config to a new location
 3    $env:AZURE_CONFIG_DIR = "authtemp"
 5    az login --service-principal -u $AppId -p $Secret -t $TenantId | Out-Null
 6    if (!$?) {
 7        [Console]::ResetColor()
 8        throw "Error signing in service principal $Id"
 9    }
11    # Do whatever you need to do here
13finally {
14    # Remove the temporary config and switch back to the user
15    Remove-Item $env:AZURE_CONFIG_DIR -Recurse -Force
16    $env:AZURE_CONFIG_DIR = $null

This does come with a health warning though - by switching over to a new config directory, you are also temporarily getting rid of any extensions that you have installed. After switching back they will be available to you again, but if your script requires access to an extension during the temporary session, you’ll need to remember to install it:

1az extension add --upgrade -n <EXTENSIONNAME>