Skip to content
James Dawson By James Dawson Principal I
Using multiple azure-cli credentials within automation

Have you ever needed an automated process to use alternative credentials for a subset of tasks?

Do your CI/CD processes run with least privilege and lack the permission to carry out certain higher privilege tasks like creating users, changing permissions or role assignments?

This post will demonstrate a technique that allows you setup multiple, concurrent authenticated sessions when using the azure-cli and switch freely between them.

Ordinarily when you run the az login command, your profile stored in ~/.azure will be updated with the obtained authentication token and the azure-cli will use this to authenticate subsequent commands.

Azure Weekly is a summary of the week's top Microsoft Azure news from AI to Availability Zones. Keep on top of all the latest Azure developments!

However, it is possible to override the path used to store the profile data by setting the environment variable AZURE_CONFIG_DIR. In this way your automated process can use the standard profile path for its default credentials but setup additional authenticated sessions for any other security contexts it requires to do its job.

The best hour you can spend to refine your own data strategy and leverage the latest capabilities on Azure to accelerate your road map.

You just need to ensure that this environment variable is set to point at the correct path before running your azure-cli command (and unset when you want to use the default credentials again).

The PowerShell script below should give you the general idea:

$ErrorActionPreference = 'Stop'
# setup temporary profile path for the alternative user
$altIdProfilePath = Join-Path ([io.path]::GetTempPath()) '.azure-altId'

try {
    # check whether already logged-in
    $currentToken = $(az account get-access-token) | ConvertFrom-Json
    if ([datetime]$currentToken.expiresOn -le [datetime]::Now) {
        throw
    }
}
catch {
    Write-Host 'You need to login'
    az login | Out-Null
    if ($LASTEXITCODE -ne 0) { exit 1 }
}

Write-Host "You are logged-in (default credential)"
Write-Host "Output from 'az account show':"
az account show --query user

# create a test SPN
Write-Host "`nCreating temporary SPN..."
$newUser = $(az ad sp create-for-rbac -n "My-Alt-Id" --skip-assignment) | ConvertFrom-Json
Write-Host "Created appId: $($newUser.appId)"

Write-Host "`nSwitching to alternative user ($altIdProfilePath)"
# don't use the new SPN too soon ;-)
Start-Sleep -Seconds 5
$env:AZURE_CONFIG_DIR = $altIdProfilePath
Write-Host "Logging-in as temporary SPN"
az login --service-principal -u $newUser.appId -p $newUser.password --tenant $newUser.tenant --allow-no-subscriptions | Out-Null
if ($LASTEXITCODE -ne 0) { exit 1 }
Write-Host "Output from 'az account show':"
az account show --query user

Write-Host "`nSwitching back to default credential"
# unset the environment variable
Remove-Item env:\AZURE_CONFIG_DIR
Write-Host "Output from 'az account show':"
az account show --query user

# tidy-up
Write-Host "`nRemoving temporary SPN..."
az ad sp delete --id $newUser.appId
Remove-Item -Recurse -Force $altIdProfilePath

FAQs

How can I use multiple Azure CLI credentials in the same automated process? Set the AZURE_CONFIG_DIR environment variable to override the default profile path. This allows your automation to maintain separate authenticated sessions - one in the default ~/.azure location and others in custom paths you specify. Each path holds its own independent credential context.
Why would I need multiple Azure CLI credentials in automation? CI/CD processes typically run with least privilege, but certain tasks like creating users, changing permissions, or managing role assignments require elevated access. Maintaining multiple credential contexts lets you switch to a higher-privilege identity only when needed, rather than running everything with excessive permissions.
How do I switch between different Azure CLI credential contexts in a script? Set the AZURE_CONFIG_DIR environment variable to point at the profile path for the credentials you want to use. When you need to return to your default credentials, simply unset or remove the environment variable - the CLI will then revert to using the standard ~/.azure location.
Where does Azure CLI store authentication tokens by default? When you run az login, your profile and authentication token are stored in ~/.azure. The CLI uses this location for all subsequent commands unless you override it with the AZURE_CONFIG_DIR environment variable, which redirects it to an alternative profile folder of your choosing.
What should I do after creating a new service principal before authenticating with it? Give it a few seconds before attempting to authenticate. There can be a brief propagation delay after creation as the identity replicates through Azure AD, so adding a short pause (around 5 seconds) in your automation helps avoid intermittent authentication failures with newly created identities.

James Dawson

Principal I

James Dawson

James is an experienced consultant with a 20+ year history of working across such wide-ranging fields as infrastructure platform design, internet security, application lifecycle management and DevOps consulting - both technical and in a coaching capacity. He enjoys solving problems, particularly those that reduce friction for others or otherwise makes them more effective.