Wednesday, August 13, 2014

Azure PowerShell non-interactive login

An interesting topic and very important for automation scenarios is how to authenticate a PowerShell script by providing credentials non-interactively.

Luckily a recent version of Azure PowerShell (0.8.6) you can provide additional –credential parameter to the Add-AzureAccount command (hopefully documentation will be updated soon to reflect this additional parameter). This is very helpful and the key point to enable non-interactive PowerShell Automations with organizational accounts (non-interactive management with PowerShell has always been possible with a Management Certificate).

In order to provide proper credentials to the Add-AzureAccount we need to properly protect our password and store it in a file, that can later be used. For this we can use the following simple PowerShell commands:

read-host -assecurestring | convertfrom-securestring | out-file d:\tmp\securestring.txt


Next we have to use the previously saved password to construct the credentials needed for Add-AzureAccount:

# use the saved password 
$password = cat d:\tmp\securestring.txt | convertto-securestring
# currently (August, the 13nd, 2014) only organizational accounts are supported (also with custom domain).
# Microsoft Accounts (Live ID) are not supported
$username = "user@tenant.onmicrosoft.com" # or user@yourdomain.com if 'yourdomain.com' is registered with AAD
$mycred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username,$password
Add-AzureAccount -credential $mycred


The whole PowerShell can also be found under the following Gist.


Credits go to Jamie Thomson and fellow MVP Mike Wood from their contribution on StackOverflow.

No comments: