Michal Checinski

Working with multiple Azure subscriptions in console

June 21, 2020 , posted under Azure
Working with multiple Azure subscriptions in console

Often there are more than one Azure subscription in one organization. The split is made to keep different projects, company divisions or environment separate. Especially the latter division is important due to security and access control.

In that approach it is painful to switch between those subscriptions, especially in the console.

How it is typically done to switch between subscripions

Usually to change subscription you just list all of the available subscriptions. Then you copy id of that subscription, and paste it into the next command. All of it is done by the two Az PowerShell commands:

Get-AzSubscription
# Here I copy subscription Id using mouse (I hope for not making any mistake)
Set-AzContext -SubscriptionId xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

That kind of operation will lead to human errors and frustrations. By the accident not all of the guid is highlited, you choose the wrong subscription etc. If you switch subscriptions many times a day, in a month you waste a lot of time due to these mistakes.

The solution is simple, and I’ll bet that everyone is using it already. It is called aliases. In powershell if you type command that lists files in the directory, you probably use ls (especially when you use the unix several times). That is an alias to the Get-ChildItem command.

How to set your own aliases? Aetting up a new alias can be done fairly easily, by using New-Alias. But tin order to those aliases be set always when you start a new PowersHell session, we need to save them in the profile.ps1 file,. To edit this file you need to write the following command in the Powershell window:

notepad.exe $Profile
# or if you use Visual Studio Code:
code $Profile

If there is no profiles file one will be created for you.

Then in the file you need to insert those lines:

Function Set-AzSubscriptionBizspark
{
    Set-AzContext -SubscriptionId xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
}

New-Alias azsubprod Set-AzSubscriptionBizspark You make as many functions and Set-Alias-es as you want to. Now if I want to change the subscription to production i just type azsubprod in the powershell. This is a huge improvement over a first version, don’t you think?