Authenticate to Azure subscription using PowerShell
The first task before working with any Azure services using PowerShell is to authenticate to your Azure subscription. Below is the cmdlet that allows you to authenticate to your subscription. It prompts you to enter your login credentials. If you have enabled MFA (Multi-Factor Authentication), you will have to provide the necessary details to complete the authentication process.
The above cmdlet requires user intervention to provide credentials, now we cannot have user intervention while authenticating programmatically. The below script will help us authenticate programmatically.
# Create a text file to store the password encrypted
"P@ssworD" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | out-file "C:\pass.txt" -Force
# Load the encrypted string
$secpasswd = Get-Content "C:\pass.txt" | ConvertTo-SecureString
# Create a PS Credential object
$mycreds = New-Object System.Management.Automation.PSCredential ("<Azure_login_ID>", $secpasswd)
# Authenticate with Azure
Add-AzureRmAccount -Credential $mycreds
If your email ID is registered with multiple subscriptions, you will log in to a default subscription. The below cmdlet will list all the subscriptions that your email Id is registered with:
Any Azure PowerShell cmdlets you run henceforth will query the default subscription. That is, retrieve the details about the resources from that subscription. Use the below cmdlet to change the subscription:
Select-AzureRmSubscription -Subscription "44f62222-39b8-4b2f-9999-36d5555587f7"
Pass the “ID” that you get from Get-AzureRmSubscription cmdlet as a value to the “-Subscription” parameter.
Authenticate to Azure subscription via Azure Automation Runbook
Azure offers more than one way of automating your infrastructure. One such service is Azure Automation Account. Your runbooks will need to authenticate to your Azure environment before it can act on your Azure resources.
To achieve this, you will need a “RunAs” connection to your Azure Automation Account. Below link will help you create one using Azure Portal.
Once you have the Account set up, use the below code in the Azure Automation Runbook to authenticate with your Azure subscription:
$connectionName = "AzureRunAsConnection"
#Getting the service principal connection "AzureRunAsConnection"
$servicePrincipalConnection = Get-AutomationConnection -name $connectionName
"Logging into Azure..."
Add-AzureRmAccount -ServicePrincipal -TenantID $servicePrincipalConnection.TenantID -ApplicationID $servicePrincipalConnection.ApplicationID -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
$ErrorMessage = "Connection $connectionName not found."
Write-Error -Message $_.Exception