How to Create Azure Service Principals in PowerShell

Published:30 September 2024 - 2 min. read

Today’s sponsor is n8n, the AI-native workflow automation tool built for ITOps and DevSecOps. With 100+ templates to get you started quickly and a powerful visual editor, you can automate complex workflows without giving up control. Check it out here.

In this blog post, you’ll learn how to create an Azure service principal using PowerShell, which is essential for automating tasks and securely managing resources in Azure. We will walk through the process of creating an Azure Active Directory (AD) application, generating a client secret, and assigning the necessary permissions for managing virtual machines (VMs). This method allows applications to securely authenticate and interact with Azure resources.

Step 1: Install Required Azure Modules

Start by installing the necessary module, `Az.Resources`, which contains the cmdlets required to manage Azure resources, including creating and managing Azure AD applications and service principals.

Install-Module -Name Az.Resources

Step 2: Create an Azure AD Application

Now, create an Azure AD application, which acts as the identity for managing Azure resources. Here, we create an app called “VMManagement” that will be used for managing virtual machines.

$vmManagementApp = New-AzADApplication -DisplayName VMManagement

Step 3: Create a Service Principal

After creating the Azure AD application, generate a service principal. This principal allows us to manage resources in Azure using the app’s identity.

$sp = New-AzADServicePrincipal -ApplicationId $vmManagementApp.AppId

Step 4: Generate a Client Secret

We now need to create a client secret that the service principal will use for authentication. This secret is generated and stored securely.

$clientSecret = New-AzADAppCredential -ObjectId $vmManagementApp.Id
$clientSecret.SecretText | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File -FilePath C:\AzureAppPassword.txt

This command creates a client secret for the app and saves it in an encrypted format to a file. This file will be used later to authenticate the application.

Step 5: Assign Permissions to the Service Principal

The next step is to assign the necessary roles to the service principal. In this case, we grant the “Virtual Machine Contributor” role, allowing the service principal to manage VMs.

$subscriptionId = (Get-AzSubscription).Id
New-AzRoleAssignment -ObjectId $sp.Id -RoleDefinitionName "Virtual Machine Contributor" -Scope "/subscriptions/$subscriptionId"

This grants the service principal permissions to manage VMs in the specified subscription.

Step 6: Authenticate Using the Service Principal

To test the authentication, use the client secret stored earlier to log in with the service principal.

$pass = (Get-Content -Path 'C:\AzureAppPassword.txt' | ConvertTo-SecureString)
$azureAppCred = New-Object System.Management.Automation.PSCredential($vmManagementApp.AppId, $pass)
$subscription = Get-AzSubscription
Connect-AzAccount -ServicePrincipal -SubscriptionId $subscription.Id -TenantId $subscription.TenantId -Credential $azureAppCred

This command authenticates the service principal using the application ID and the secure password.

Step 7: Test the Authentication

Now that you’ve authenticated, test the authentication by retrieving a list of virtual machines in the subscription.

Get-AzVM

If successful, the command will return a list of VMs, confirming that the service principal is working as expected.

Step 8: Rotate Client Secrets

For security, it’s essential to periodically rotate client secrets. The script below automates this process, generating a new client secret and removing the old one.

[CmdletBinding()]
param(
    [Parameter(Mandatory)]
    [string]$AdApplicationName,

    [Parameter()]
    [string]$OutputFilePath = "C:\NewAzureAppPassword.txt"
)

$adApp = Get-AzADApplication -DisplayName $AdApplicationName
$sp = Get-AzADServicePrincipal -ApplicationId $adApp.AppId
$newClientSecret = New-AzADAppCredential -ObjectId $adApp.Id
$newClientSecret.SecretText | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File -FilePath $OutputFilePath

$oldClientSecret = (Get-AzADApplication -DisplayName $AdApplicationName).PasswordCredentials | Sort-Object StartDateTime | select -First 1
Remove-AzADAppCredential -ApplicationId $adApp.AppId -KeyId $oldClientSecret.KeyId

This script rotates the client secret, generating a new one and securely saving it to a file.

Conclusion

By following these steps, you’ve successfully created a service principal, granted it the necessary permissions, authenticated using the client secret, and tested it. Additionally, you’ve implemented a process to rotate client secrets regularly, enhancing the security of your Azure applications. This setup ensures your automation scripts can securely access and manage Azure resources without manual intervention.

Hate ads? Want to support the writer? Get many of our tutorials packaged as an ATA Guidebook.

Explore ATA Guidebooks

Looks like you're offline!