Prashanth Jayaram
Find the version table to analyze the workflow

Different ways to login to Azure automation using PowerShell

December 22, 2020 by

PowerShell becomes a de facto toolset in the arsenal of Azure automation. PowerShell provides a platform and a friendly way of automating many repeated tasks, which in turn minimize the time-and-cost. PowerShell always comes to the rescue when there is a need for automation, and it is no different for Azure. If you are already familiar with PowerShell cmdlets, then it will be easy to be acquainted with Azure PowerShell modules. For Azure automation, Microsoft provided a set of Azure PowerShell Modules that can be leverage to manage the Azure Cloud platform.

In this article, you will see different ways to connect to Azure. I will discuss the following ways to connect to Azure using PowerShell.

  1. Introduction to Connect-AzAccount cmdlet
  2. Login using Connect-AzAccount
  3. Connect using credentials
  4. How to encrypt the credentials
  5. Interactive sign-in using Azure portal
  6. How to create a profile
  7. Use profile to login to Azure console
  8. And more…

Introduction

Before we write PowerShell script for Azure, you must sign into the Azure portal and then build the automation. We login to the portal by type in the user-id and password and set the session to appropriate the subscription context.

  • Note: In the Azure automation script, sometimes you may see the use of Login-AzAccount; you can also see Add-AzAccount; and some may use Connect-AzAccount. The basic question is which one is correct and why?. To answer all three cmdlets holds well in all the scenarios. Any of the three cmdlets can log in to Azure—It looks different but all three commands can be used to authenticate Azure using PowerShell.Connect-AzAccount is the command and Login-AzAccount and Add-AzAccount are the aliases build around the Connect-AzAccount cmdlet

PS:\> Get-command *AzAccount* -Module *Az*

List azure account

Prepare the Azure Automation script

The first step in the exercise, login to the Azure subscription. In this example, we will explore the different ways to login into the portal.

Using Login-AzAccount

In this section, we will learn how to use the credential parameter to login and setup azure automation. In this case, login-AzAccount cmdlet accepts the credentials to run the session with the context of the specified user. In order to do that declare the variables to hold the values of username and password. You can directly feed values to the cmdlets as well. When you interactively run the script, you can feed the credentials. The real challenge comes when you want to immerse the credentials in your automation.

# Open the PowerShell ISE and type in the following commands :

Login-AzAccount -Credential (Get-Credential)

  • Note: In the aforementioned method, we cannot run the script unattended. But we can instantiate the credential object using the New-Object System.Management.Automation.PSCredential namespace accepts the username and password parameters. The username is plain text and the password is a secure string that serves as the password

To convert SecureString run the password along with the ConvertTo-SecureString cmdlet. Let us go ahead and define the username and password in clear texts.

$username = “pjayaram@gmail.com”
$password=”abcd#$@#$@!@#1234″

To convert the password into a secure string, run the following ConvertTo-SecureString cmdlet.

$SecurePassword = ConvertTo-SecureString “$password” -AsPlainText -Force

Next, we need to pass the parameters to the PSCredential object to prepare the credentials.

$credentials = New-Object System.Management.Automation.PSCredential($username, $SecurePassword)

  • Note: The $credentials(PSCredential) object can be fed to any cmdlet accepting the -PSCredential parameter. In the following example, you can see the use of –Credential parameter:
    \>Get-WmiObject -class Win32_Service –Computer <ServerName> -Credential $credentials

Run the below command to login to the Azure Portal:

Login-AzAccount -Credential $credentials

How to encrypt the credentials

We understand from the above step that we can execute the Azure automation script unattended, but what about security? Anyone who have the access to the file location can open and read the password. Let us deep dive more into the other option to find out secured options. Let us convert the clear texts into security string and save the content in the specified location. In this case, convert the password “asbcd#@#$%%!” and store it in a d:\password\password.txt.

(Get-Credential).password | ConvertFrom-SecureString | set-content “D:\Password\password.txt”

The password in the D:\password\password.txt is encrypted. In this way, we are providing another layer of security.

$file = “D:\Password\password.txt”
$UserName = “SVCSQLAZ@pepsico.com”
$Password = Get-Content $file | ConvertTo-SecureString
$credential = New-Object System.Management.Automation.PsCredential($UserName, $Password)
# Login to the Azure console
Login-AzAccount -Credential $credential

Interactive sign-in

In this section, you will see the interactively type in the username and password.

Pass credentials

Let us save the credentials by tying the username and password

Type in the credential to connect to Azure

Store the credential automation workflow

On PowerShell Core version, username and password authentication is not supported.

PS D:\ > $cred = New-Object System.Management.Automation.PSCredential($username, $SecurePassword)
PS D:\PS_Scripts\BuildScript> Login-AzAccount -Credential $cred

Error:

  • Connect-AzAccount: Username + Password authentication is not supported in PowerShell Core. Please use device code authentication for interactive log in, or Service Principal Authentication for script log in.

You can query the $PSVersionTable environment variable to see the PowerShell version to ensure that we are getting the error in the PowerShell core version.

Find the version table to analyze the  workflow

  • Note: To list all the environment variables, run Get-ChildItem or Get-Item along with ENV: variable:Get-ChildItem Env: or Get-Item ENV:

Interactive sign-in using Azure portal

The Connect-AzAccount uses the default authentication of the device used to interactively connecting to Azure using PowerShell.

PS D:\PS_Scripts\BuildScript> Login-AzAccount

  • WARNING: To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code RXS3SJJXL to authenticate

PowerShell directs to a GUI to type in the device code and then redirect you to type in username and password

Type in the Device code in the process of validating the MFA workflow

Type in the credentials as part of MFA for Azure

You can see the connection is successful.

Azure connection succesful screen

After that, you can see the PowerShell prompt available for use.

Azure automation using device code authentication

You can see that you are established in the session.

Using profile to connect to Azure

In the next example, we will see how to create the profile and use the profile in the Azure automation. There are different ways to save the Azure profile. We save the profile in a file using Windows PowerShell console or Cloud Shell. Make sure on the Windows PowerShell you loaded have the Az module installed and imported, and it is ready to use.

The steps and commands remain the same for both the options, but if you choose Cloud Shell, you may need to download and copy them to the target server where you want to run the automation.

Open the PowerShell console. Run Add-AzAccount or Connect-AzAccount or Login-AzAccount command.

Browse the URL and type in the device code as part of automation login authentication method

You must authenticate the device and type in Azure credentials in the pop-up dialog box

Type in the device code for Azure Automation

After the successful authentication validation, it will direct you to the PowerShell console.

Succesful authentication screen

To create a profile, run the following command

Automation authentication through profile

To see the profile file details, you can run the ls -lrt command to view the time and other details of JSON.

To download the file in Cloud Shell, use the download icon and type the filename and Click Download

Download the profile to validate the authentication using PowerShell

Next, you can copy the file on the target server where you run the automation script.

Copy the file to the target to validate the authentication in Azure automation script

  • Note: I will save the Azure subscription details in the MyAzureDemoProfile.JSON. The profile is saved in JSON format. It is easy to explore the data in the JSON file just using a text pad or notepad or any editor of your choice. The advantage is that you can refer to the JSON tags in PowerShell automation scripts without typing the credentials of Azure account all the time when you want to run the Azure automation scripts in within the scope of another session context

The PowerShell code to log in to Azure account using a profile.

  • Note: $profilePath is the path of the profile

The Set-AzContext checks the profile details using the Azure profile file. If discovered, it retrieves the subscription ID of the profile and sets the context of the current scope of the specified subscription.

Summary

Azure PowerShell supports different authentication methods to develop Azure automation scripts. The easiest among them is to get started with Cloud Shell. It automatically loads the Azure modules. In addition, it allows you to interactively sign in through the browser to perform the required authentication to get into Azure. The recommended way to write an automation script is by using the Service principal with the required privileges. In addition, you can also try to use encrypted credentials. By default, Azure runs cmdlets against the first subscription. If your account is part of multiple subscriptions and you need to change the active subscription run the Set-AzContext cmdlet along with subscriptionId.

That is all for now….

Table of contents

IT Cloud Automation using PowerShell
Deep dive into IT Cloud Automation using PowerShell
Getting started with Azure Automation
Getting started with Azure SQL Database using Azure CLI
Provisioning SQL Server 2019 Azure Container Instance using PowerShell
Four different methods to copy your Azure SQL database
Azure SQL Database vs SQL Server on Azure VMs
How to provision Azure SQL Database using Ansible
Quick start guide to Geo-restore in Azure SQL Database
Different ways to login to Azure automation using PowerShell
How to perform Azure SQL database Import/Export operations using PowerShell
How to set up Azure Data Sync between Azure SQL databases and on-premises SQL Server

Prashanth Jayaram
Azure, PowerShell

About Prashanth Jayaram

I’m a Database technologist having 11+ years of rich, hands-on experience on Database technologies. I am Microsoft Certified Professional and backed with a Degree in Master of Computer Application. My specialty lies in designing & implementing High availability solutions and cross-platform DB Migration. The technologies currently working on are SQL Server, PowerShell, Oracle and MongoDB. View all posts by Prashanth Jayaram

7,428 Views