Loading...

Using Managed Identity with Azure Automation & PnP.PowerShell

Using Managed Identity with Azure Automation & PnP.PowerShell
Featured image of post Using Managed Identity with Azure Automation & PnP.PowerShell

How to Set Up a Managed Identity for Azure Automation Runbooks and Use It in PowerShell Scripts with PnP.PowerShell

This guide walks you through setting up a managed identity in Azure Automation Runbooks and using it in PowerShell scripts with PnP.PowerShell. It also covers local testing using Visual Studio Code. By the end, you’ll have a secure, maintainable, and efficient automation workflow.


1. Introduction

Azure Automation is a powerful tool for automating tasks across Azure resources. By using managed identities, you can securely access resources without storing credentials in your scripts. This approach reduces security risks and simplifies authentication. When combined with PowerShell 7.2 and PnP.PowerShell, you can automate tasks for SharePoint Online, Microsoft Graph, and other Azure services seamlessly.

In this guide, you’ll learn how to:

  • Enable and configure a managed identity in Azure Automation Runbooks.
  • Assign permissions to the managed identity.
  • Write and test PowerShell scripts that use the managed identity with PnP.PowerShell.
  • Debug and test scripts locally using Visual Studio Code.

2. What Are Managed Identities?

Managed identities are Azure’s way of securely handling authentication for services. They come in two types:

  • System-assigned: Tied to a specific resource (e.g., an Automation Account) and automatically managed.
  • User-assigned: Created independently and can be shared across multiple resources.

For Azure Automation, system-assigned identities are the easiest to use. They are created and deleted with the Automation Account, ensuring no orphaned credentials remain.

Why Use Managed Identities?

  • No need to store credentials in scripts, variables, or Azure Key Vault.
  • Secure access to Azure resources like SharePoint Online, Microsoft Graph, and Key Vault.
  • Simplified lifecycle management.

3. Setting Up a Managed Identity in Azure Automation

Step 1: Create or Enable a Managed Identity

  1. Create a New Automation Account:

    • Go to the Azure Portal.
    • Create a new Automation Account and enable the system-assigned managed identity under the “Advanced” tab.
  2. Enable Managed Identity for an Existing Account:

    • Navigate to your Automation Account in the Azure Portal.
    • Go to Account Settings > Identity and toggle the system-assigned identity to “On” and click save.
    • Note the Principal ID for assigning permissions later.
  3. Assign Azure roles to the managed identity:
    After enabling the managed identity, you need to assign it the necessary Azure roles to access resources:

    • Go to the Identity if you just created the Automation Account.
    • Click on Azure role assignments.
    • Click on Add role assignment and assign at least the read permissions for the resource group. This lets the managed identity access the resources in that group (e.g., Variables, etc. in Azure Automation).

Step 2: Assign Permissions

Grant the managed identity access to the resources your script will interact with:

  • For example you need the following roles for your PowerShell script Group.ReadWrite.All and Sites.FullControl.All
    If you want to list all permissions available for the managed identity, you can use the following command:
1
2
3
4
5
6
7
8
9
#Variable
$tenantId = [Tenant ID]

#Connect-AzAccount -UseDeviceAuthentication
Connect-AzAccount -TenantId $tenantId -UseDeviceAuthentication
# Microsoft Graph Application ID
$graphAppId = '00000003-0000-0000-c000-000000000000'
# Microsoft Graph Service Principal abrufen
$spGraph = Get-AzADServicePrincipal -ApplicationId $graphAppId
  • With the following script you can assign the roles to the managed identity:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#Variable
$tenantId = [Tenant ID]

#Connect-AzAccount -UseDeviceAuthentication
Connect-AzAccount -TenantId $tenantId -UseDeviceAuthentication

# Managed Identity Service Principal abrufen
$managedIdentity = Get-AzADServicePrincipal -DisplayName '[Name of your Automation Account]'

# Assign all specified permissions
$requiredPermissions = @(
    'Group.ReadWrite.All',
    'Sites.FullControl.All',
)

foreach ($permissionName in $requiredPermissions) {
    $permission = $spGraph.AppRole | Where-Object { $_.Value -eq $permissionName }
    if ($permission) {
    Write-Host "Attempting to assign permission: $($permission.Value) with ID: $($permission.Id)"
    try {
        New-AzADServicePrincipalAppRoleAssignment `
        -ServicePrincipalId $managedIdentity[1].Id ` #You could also use the Managed Identity ID directly
        -AppRoleId $permission.Id `
        -ResourceId $spGraph.Id
        Write-Host "Successfully assigned permission: $permissionName" -ForegroundColor Green
    }
    catch {
        Write-Host "Failed to assign permission: $permissionName" -ForegroundColor Red
        Write-Host $_.Exception.Message
    }
    }
}

4. Writing PowerShell Scripts with PnP.PowerShell

Step 1: Install PnP.PowerShell

  1. Locally:
    Run:
    1
    
    Install-Module -Name PnP.PowerShell -Scope CurrentUser
    
  2. In Azure Automation:
    • Go to your Automation Account in the Azure Portal.
    • My Advice: Create Runtime Environment with PowerShell 7.2.
    • Go to Packages Tab and add the PnP.PowerShell module and other PowerShell modules you need.
    • Click Add from gallery and search for PnP.PowerShell.
    • Select the module and click Select in the lower left corner.
    • Click Create to create the runtime environment with the selected modules.

Step 2: Example Script

Now we can write a PowerShell script that uses the managed identity to connect to SharePoint Online and perform operations. Below is an example script that retrieves site details based on a group ID passed as a parameter.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Param
(
    [Parameter(Mandatory = $true)]
    [object]$SiteData  # Expects data like a group ID for operations.
)

$ErrorActionPreference = 'Stop'

# Retrieve variables from Azure Automation
$TenantName = Get-AutomationVariable -Name 'TenantName'
$GroupId = $SiteData.groupid

# Connect to SharePoint Online using the managed identity
try {
    Connect-PnPOnline -Url "https://$($TenantName).sharepoint.com" -ManagedIdentity
    Write-Verbose 'Connected to SharePoint Online'
}
catch {
    Write-Error "Failed to connect: $_"
}

# Perform operations (e.g., retrieve site details)
$Site = Get-PnPTenantSite -Detailed -Identity $GroupId 
Write-Output "Site URL: $($Site.Url)"

Key Points:

  • The Connect-PnPOnline cmdlet supports managed identity authentication.
  • Use Get-AutomationVariable to retrieve variables stored in Azure Automation.

5. Testing and Debugging Locally with Visual Studio Code

Step 1: Set Up Your Environment

  1. Install PowerShell 7.2 from the official repository.
  2. Install the PnP.PowerShell module:
    1
    
    Install-Module -Name PnP.PowerShell -Scope CurrentUser
    
  3. Install the Az and Az.Accounts modules and other modules you need:
    1
    2
    
    Install-Module -Name Az -Scope CurrentUser
    Install-Module -Name Az.Accounts -Scope CurrentUser
    

Step 2: Set Up Visual Studio Code

  1. Install Visual Studio Code from the official site.
  2. Install the Azure Automation extension for VS Code.

Step 3: Debug in Visual Studio Code

  • Open your script in VS Code by signing into your Azure account in the Azure Automation extension.
  • Double click on the script file to open it.
  • Since you are now signed into the Automation Account, you can run all the commands directly in VS Code (e.g getting variables, etc. from the Automation Account).

6. Best Practices

  1. Follow RBAC Principles: Assign only the permissions the managed identity needs.
  2. Enable Logging: Use verbose logging in your scripts and monitor runbook execution in Azure Automation.
  3. Test Thoroughly: Test scripts locally and in a staging environment before deploying to production.

7. Conclusion

By following this guide, using managed identities in Azure Automation simplifies authentication and enhances security.

For more details, check out:

Let me know if you have tried this approach or if you have any questions in the comments below!

Published on:

Learn more
Need help with this product?

We can help you with Using Managed Identity with Azure Automation & PnP.PowerShell

If you want help implementing, troubleshooting, or improving this product, contact us and we’ll point you in the right direction.

The State of the Microsoft 365 Nation
The State of the Microsoft 365 Nation

Recent content on The State of the Microsoft 365 Nation

Share post:

Related posts

Creating Copilot Studio Agents Without an M365 Copilot Premium License

A common assumption when getting started with Copilot Studio is that you need a full Microsoft 365 Copilot Premium license. That assumption is...

5 months ago

Power Automate: Get events (V4) shared mailbox fix

When your flow reads a shared mailbox calendar using the Office 365 Outlook → Get events (V4) connector, it can fail in a way that looks like...

6 months ago

UPDATED - Set Up Pay-as-you-go M365 Chat & SharePoint Agents

Introduction to Pay-as-You-Go Agents in Microsoft 365 Microsoft has introduced a flexible way for organizations to leverage AI capabilities wi...

1 year ago

How to Use Flexible Sections in SharePoint Pages and News

If you’ve been using SharePoint Online to build pages or share news, you know how important it is to have a layout that works for your c...

1 year ago

What's New in SharePoint Pages

1. New Carousel Layout in the Hero Web Part The Hero Web Part has always been a fundamental element of SharePoint pages. The new Carousel Layo...

1 year ago

Power Platform Solutions Made Simple

Introduction to Power Platform Solutions Power Platform Solutions offer many benefits, especially when moving from standalone flows and apps t...

1 year ago

Use your Bluesky post for comments on your Hugo Blog

Since Bluesky is getting really popular by people I interact with, I decided to switch my blog comments to Bluesky posts. In this blog post, I...

1 year ago

Exploring SharePoint Online's SiteAssets Library

The SiteAssets library in SharePoint Online often seems like a mystery to a lot of users I talk to, but it’s important to understand it ...

1 year ago

Step-by-Step Guide to Copy Pages between SharePoint Online

Unfortunately you can’t copy pages in SharePoint through the UI. But sometimes you may need to copy pages and their associated SiteAsset...

1 year ago

Re-creating Multilanguage Links: A Step-by-Step Guide

Maybe you’ve also stumbled upon the issue of missing multilanguage links in your SitePages library in SharePoint Online. This can happen...

1 year ago

Newsletter

Get the latest Dynamics 365 and Power Platform content in your inbox

A curated digest of community blogs, product news, videos, and podcasts — delivered without the noise.

Weekly updates Unsubscribe anytime Fresh community picks
We use your email only for the newsletter and you can unsubscribe at any time.
By subscribing, you agree to the privacy policy.