Connecting to Azure with Azure PowerShell Module

Today I am going to show you how to connect to Azure with the PowerShell Module. There are a few things that you should have in place before trying to connect. You will need to have an Azure Subscription and I recommend setting up Azure AD. I am not going to cover how to get Azure AD setup in this series, there are many blog post out there already on how to setup Azure AD Connect and ADFS.

What Credential should you use to connect to Azure, my recommendation is that you use an organization account that you have granted access to your Azure subscription. You have the option to use an Azure AD account also but if you have signed up to azure with a personal outlook.com or gmail address you will not be able to authenticate to Azure with that account using the scripts below.  You will get this error

Add-AzureAccount : -Credential parameter can only be used with Organization ID

credentials.

If you are running the Azure PowerShell module from your desktop you can use the following 3 lines to get connected to Azure.

$Cred = Get-Credential 
$Account = Add-AzureAccount -Credential $Cred
Select-AzureSubscription -SubscriptionId '<GUID>' 

If you are running the Azure PowerShell module from Azure Automation you can use this workflow as a template.

workflow ConnectToAzure
{
    #The name of the Automation Credential Asset this runbook will use to authenticate to Azure.
    $CredentialAssetName = 'DefaultAzureCredential'

    #Get the credential with the above name from the Automation Asset store
    $Cred = Get-AutomationPSCredential -Name $CredentialAssetName
    if(!$Cred) {
        Throw "Could not find an Automation Credential Asset named '${CredentialAssetName}'. Make sure you have created one in this Automation Account."
    }

    #Connect to your Azure Account
    $Account = Add-AzureAccount -Credential $Cred
    if(!$Account) {
        Throw "Could not authenticate to Azure using the credential asset '${CredentialAssetName}'. Make sure the user name and password are correct."
    }

    
    Select-AzureSubscription -SubscriptionID '<Guid>'
    
} 

To use the above workflow you will need to create an credential asset in Azure Automation, I will cover this more in one of the Azure Automation blog post.

Deploying Azure Resources with Azure Automation Blog Series

Leave a Reply

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