Authenticating to Azure with AzCli og the Az Powershell module

When you only have access to one Azure directory, AzCLI and the Az Powershell module can figure out the Authentication itself, but if you have access to multiple directories on one user, you have to be more specific – especially if one of the directories uses MFA.
The typical “Get started” introductions does not cover this.

I have not tried it with multiple directories all requiring (different) MFA…

AzCLI:

Make sure to use “az login” with the tenant parameter for the MFA directory. The tenant guid can be found in several places – among others in the “Show diagnostics” in the Azure portal

az login --tenant deadbeef-0000-0000-0000-000000000000

The AzCLI tool will remember your login-session for some time.

The accessible subscriptions can then be listed with:

az account list --output table

and the default subscription can be set with:

az account set --subscription deadbeef-1111-2222-3333-000000000000

Powershell Az module:

Import-Module Az

Connect-AzAccount -Tenant deadbeef-0000-0000-0000-000000000000 -Subscription deadbeef-1111-2222-3333-000000000000

When you are connected, Powershell will by default remember your login-session, and you can change subscriptions with

Set-AzContext -SubscriptionId "deadbeef-1111-2222-3333-000000000000"

As mentioned here, it is in general better to login using a service principal (like for a CI agent or unattended runs), but you might not always have the possibility to get a SP.

You can see how to create a new service principal here
https://docs.microsoft.com/en-us/cli/azure/create-an-azure-service-principal-azure-cli?view=azure-cli-latest
and how to login using it here
https://docs.microsoft.com/en-us/cli/azure/authenticate-azure-cli?view=azure-cli-latest#sign-in-with-a-service-principal
assign new password to Service Principal
https://docs.microsoft.com/en-us/cli/azure/create-an-azure-service-principal-azure-cli

Leave a Reply

Your email address will not be published. Required fields are marked *