Allan Xu
Allan Xu

Reputation: 9378

How to call Azure PowerShell Module commands in Azure Functions 3.x PowerShell 7?

I need to run Azure PowerShell Module commands (https://learn.microsoft.com/en-us/powershell/azure/install-az-ps?view=azps-5.2.0) scripts in an Azure Functions 3.

I prefer not to run Install-Module on every function call. I expect there is a better way of doing it. Azure PowerShell Module is fairly big.

I am going through the following documentation and I am not able to find any reference on how to call Azure PowerShell Module commandsL https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-powershell?tabs=portal

How to call Azure PowerShell Module commands in Azure Functions 3.x PowerShell 7?

Upvotes: 3

Views: 4142

Answers (2)

Joy Wang
Joy Wang

Reputation: 42163

No need to use Install-Module in this case, currently, when you create the powershell function in the portal, it will install the Az module for you by default via the Dependency management feature.

You could check the App files blade in the portal to make sure your function app was configured correctly, if not, change them like below.

host.json

{
  "version": "2.0",
  "managedDependency": {
    "Enabled": true
  },
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[1.*, 2.0.0)"
  }
}

requirements.psd1

@{
    # For latest supported version, go to 'https://www.powershellgallery.com/packages/Az'. 
    'Az' = '5.*'
}

profile.ps1

if ($env:MSI_SECRET) {
    Disable-AzContextAutosave -Scope Process | Out-Null
    Connect-AzAccount -Identity
}

With the settings above, the function app will install Az module for you automatically and login Az module with MSI(managed identity) of your function app(command in profile.ps1 did it), it is convenient.

To use Az commands in the function, you just need to enable the MSI for your function app and assign the RBAC role to your MSI(depend on specific case, e.g. if you want to list all the web apps in your subscription/resource group, you need give the role like Reader to your MSI at the subscription/resource group scope).

enter image description here

Then in your function code, just use the Az command directly without anything else.

Sample:

$a = Get-AzWebApp -ResourceGroupName joyRG
Write-Host $a.Name

enter image description here

Upvotes: 4

BrettMiller
BrettMiller

Reputation: 1046

In your Azure Functions workspace you have a requirements.psd1 which lists dependencies, the only default module that it imports is the Az module.

As this is available when the host starts you should just be able to use auto-loading by utilising the Az commands in your function run.ps1.

If you only need a subset of Az modules then you can be more specific in your requirements.psd1 file.

'Az.Accounts' = '1.9.5'
'Az.Resources' = '2.*'

This is listed in the docs here: Azure Functions Developer Reference

Upvotes: 4

Related Questions