AzureRM tasks in PowerShell Automation using Azure AD Principal - Part One

So you need to run a PowerShell script inside a Azure Automation account and the script uses AzureRM cmdlets. How would you authenticate? Do you use a user account? But the user account could have more permissions than what is actually required for your script, opening a whole discussion around security. I have also seen organizations create user accounts that are used as service accounts. But what does Microsoft say?

"Automated tools that use Azure services should always have restricted permissions. Instead of having applications sign in as a fully privileged user, Azure offers service principals."

So what is an Azure Service Principal?

An Azure service principal is an identity created for use with applications, hosted services, and automated tools to access Azure resources. This access is restricted by the roles assigned to the service principal, giving you control over which resources can be accessed and at which level. 

Service Principals offer 2 kinds of authentication
  1. Password-based authentication
  2. Certificate-based authentication
At this point, I assume that you already have created an automation account in your tenant. Also, you can create a runbook that can run within the automation account.

First let us look at the ways to create service principals.

Password-based (with own password)

Import-Module Az.Resources # Imports the PSADPasswordCredential object
$credentials = New-Object Microsoft.Azure.Commands.ActiveDirectory.PSADPasswordCredential -Property @{ StartDate=Get-Date; EndDate=Get-Date -Year 2024; Password=<Choose a strong password>}
$sp = New-AzAdServicePrincipal -DisplayName ServicePrincipalName -PasswordCredential $credentials

The object returned from New-AzADServicePrincipal contains the Id and DisplayName members, either of which can be used for sign in with the service principal.

It is also possible to create a service principal with a random generated password. Please check the Microsoft documentation for details. Reference at the end of the post.

Certificate-based

$cert = <public certificate as base64-encoded string>
$credentials = New-Object Microsoft.Azure.Commands.ActiveDirectory.PSADKeyCredential -Property @{ StartDate=Get-Date; EndDate=Get-Date -Year 2024; KeyId=New-Guid; CertValue=$cert}
$sp = New-AzADServicePrincipal -DisplayName ServicePrincipalName -KeyCredential $credentials

Now that we have created the service principal, in the Part 2 we will look at using the service principal in a runbook within an automation account.

Comments

Popular posts from this blog

Automate Import of Functions/WebAPI in Azure API Management as backend and using OpenAPI definition and Terraform

Transcripts with Microsoft Bot Framework v4

Managing built-in cache in Azure API Management