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
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

Silently Update SharePoint Metadata with PnP PowerShell

Why Bother with Metadata? Think of metadata as the DNA of your SharePoint content. It tells you who created a document, when it was last touch...

2 years ago

New Editing Options for Image Web Part in SharePoint Online

Adding and Editing Images with the Image Web Part The Image web part simplifies the process of adding visual elements to your SharePoint Onlin...

2 years ago

External User Access Reviews in Office 365

Understanding External User Access Before diving into the reviews, it’s important to understand what external access entails. External u...

2 years ago

Power Automate - How-to Posting on BlueSky and Mastodon

Introduction Do you want to save time and effort by automating your social media posts across different platforms? Do you want to learn how to...

2 years ago

M365 Groups: Set Up a 'No Owner Policy' & why it's Important

Introduction Managing group ownership is crucial for maintaining order and security within an organization in Microsoft 365. A “No Owner...

2 years ago

Social media content creator with AI Promts

Prerequisites For this tutorial you need the following: A premium Power Automate account, e.g. a Power Automate per user plan or an Powerapps...

2 years ago

Change SharePoint group to Security Groups with PowerShell

Automating SharePoint Permissions with PowerShell Managing SharePoint user permissions can be a complex and time-consuming task, especially fo...

2 years ago

Deleting doublettes in SharePoint list with PnP PowerShell

In this blog post, I will break down a PnP PowerShell script that is designed to connect to a SharePoint site, retrieve a list of users from a...

2 years ago

Limit Copilot's access to SharePoint Sites and Content

Why Permissions in Office365 matter for Copilot In the ever changing digital landscape, managing permissions and ensuring data security are pa...

2 years ago

Microsoft Teams Channel Types: How to Choose the Right One

Introduction Microsoft Teams is a powerful collaboration tool that allows you to communicate, share, and work with your team members in a secu...

2 years ago
Stay up to date with latest Microsoft Dynamics 365 and Power Platform news!
* Yes, I agree to the privacy policy