0

Azure PowerShell function works locally in VS Code successfully. However, when deployed to a function and run in Azure portal, it fails with the following error:

2023-12-14T21:05:44Z   [Verbose]   Sending invocation id: '3e85a40a-a930-78d8-be83-f53bd9847ab1
2023-12-14T21:05:44Z   [Verbose]   Posting invocation id:3e85a40a-a930-78d8-be83-f53bd9847ab1 on workerId:e8588e50-b2ad-4012-bf5b-92df7aa00739
2023-12-14T21:05:44Z   [Warning]   The Function app may be missing the 'Az.Accounts' module. If 'Az.Accounts' is available on the PowerShell Gallery, add a reference to this module to requirements.psd1. Make sure this module is compatible with PowerShell 7. For more details, see [here](https://aka.ms/functions-powershell-managed-dependency).
2023-12-14T21:05:44Z   [Error]   ERROR: The specified module 'Az.Accounts' was not loaded because no valid module file was found in any module directory.

Exception             : 
    Type    : System.IO.FileNotFoundException
    Message : The specified module 'Az.Accounts' was not loaded because no valid module file was found in any module directory.
    HResult : -2147024894
TargetObject          : Az.Accounts
CategoryInfo          : ResourceUnavailable: (Az.Accounts:String) [Import-Module], FileNotFoundException
FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand
InvocationInfo        : 
    MyCommand        : Import-Module
    ScriptLineNumber : 9
    OffsetInLine     : 1
    HistoryId        : 1
    ScriptName       : C:\home\site\wwwroot\Func_Sample_1\run.ps1
    Line             : Import-Module Az.Accounts -Force
                       
    PositionMessage  : At C:\home\site\wwwroot\Func_Sample_1\run.ps1:9 char:1
                       + Import-Module Az.Accounts -Force
                       + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    PSScriptRoot     : C:\home\site\wwwroot\Func_Sample_1
    PSCommandPath    : C:\home\site\wwwroot\Func_Sample_1\run.ps1
    InvocationName   : Import-Module
    CommandOrigin    : Internal
ScriptStackTrace      : at <ScriptBlock>, C:\home\site\wwwroot\Func_Sample_1\run.ps1: line 9
PipelineIterationInfo : 

[... Repeat for 'Az.Resources' and 'SqlServer' ...]

requirements.psd1:

# See [here](https://aka.ms/functionsmanageddependency) for additional information.
@{
    'Az.Accounts' = '2.*' 
    'Az.Resources' = '6.*' 
    'SqlServer' = '22.*'
}

# run.ps1:

using namespace System.Data.SqlClient

param($Request, $TriggerMetadata)

# Import the necessary modules
Import-Module Az.Accounts -Force
Import-Module Az.Resources -Force
Import-Module SqlServer -Force

# Authenticate to Azure
Connect-AzAccount
Write-Host "Request database access token for managed identity"
$MI_Token = (Get-AzAccessToken -ResourceUrl https://database.windows.net ).Token

Verified that the modules added in requirements.psd1 are available in the PowerShell Gallery. My understanding is that modules should be downloaded automatically if they are available in the PowerShell Gallery. However, it fails in the portal. Tried manually copying the modules into the site wwwroot\Modules folder, but it still didn't help. Running out of ideas on what's missing and how to fix it. Any help would be greatly appreciated! Thank you.

2
  • Did you follow this? Commented Dec 14, 2023 at 23:18
  • Thanks for your response! Yes, I followed that article. Commented Dec 18, 2023 at 1:58

2 Answers 2

0

Thanks @Ian-kemp for the comment.

If the modules which you need are available on the PowerShell Gallery, you can use them in PowerShell Functions using the Managed Dependencies.

  • Enable the Managed Dependencies feature in the host.json and mention your modules in the requirements.psd1.

Azure Functions will make sure these modules are installed and available for the functions.

  • Check the available Powershell modules with the command Get-Module -ListAvailable:

enter image description here enter image description here enter image description here

  • I have created a PowerShell function and deployed to Azure function App:
using namespace System.Data.SqlClient

param($Request, $TriggerMetadata)


# Import the necessary modules
Import-Module Az.Accounts -Force
Import-Module Az.Resources -Force
Import-Module SqlServer -Force

# Authenticate to Azure
Connect-AzAccount
Write-Host "Request database access token for managed identity"
$MI_Token = (Get-AzAccessToken -ResourceUrl https://database.windows.net ).Token

profile.ps1:

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

requirements.psd1:

@{
'Az'='2.*'
'SqlServer'  =  '22.*'
}

host.json:

{
  "version": "2.0",
  "logging": {
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": true,
        "excludedTypes": "Request"
      }
    }
  },
  "managedDependency": {
    "enabled": true
  },
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[4.*, 5.0.0)"
  }
}

Portal Reponse:

enter image description here

References:

https://stackoverflow.com/a/57914450/19991670

Sign up to request clarification or add additional context in comments.

Comments

0

Thanks for looking into this @Pravallika.

This is what I did following your comments:

  1. Created a new function app in the portal

  2. run.ps1

             using namespace System.Net
             using namespace System.Data.SqlClient
    
             param($Request, $TriggerMetadata)
    
    
             Import-Module Az.Accounts -Force
             Import-Module Az.Resources -Force
             Import-Module SqlServer -Force
    
    
             # Authenticate to Azure
             Connect-AzAccount
             #Write-Host "Request database access token for managed identity"
             #$MI_Token = (Get-AzAccessToken -ResourceUrl https://database.windows.net ).Token
    
             Write-Host "PowerShell HTTP trigger function processed a request."
    
             # Interact with query parameters or the body of the request.
             $name = $Request.Query.Name
             if (-not $name) {
                 $name = $Request.Body.Name
             }
    
             $body = "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
    
             if ($name) {
                 $body = "Hello, $name. This HTTP triggered function executed successfully."
             }
    
             # Associate values to output bindings by calling 'Push-OutputBinding'.
             Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
                 StatusCode = [HttpStatusCode]::OK
                 Body = $body
             })
    
  3. host.json

             {
               "version": "2.0",
               "managedDependency": {
                 "Enabled": true
               },
               "extensionBundle": {
                 "id": "Microsoft.Azure.Functions.ExtensionBundle",
                 "version": "[4.*, 5.0.0)"
               }
             }
    
  4. requirements.psd1

             @{ 
                 'Az' = '2.*'
                 'SqlServer' = '22.*'
             }
    
  5. Profile.ps1

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

             Connected! You are now viewing logs of Function runs in the current Code + Test panel. To see all the logs for this Function, please go to 'Monitor' from the Function menu.
             2023-12-20T00:29:21Z   [Warning]   The Function app may be missing the 'Az.Accounts' module. If 'Az.Accounts' is available on the PowerShell Gallery, add a reference to this module to requirements.psd1. Make sure this module is compatible with PowerShell 7. For more details, see https://aka.ms/functions-powershell-managed-dependency.
             2023-12-20T00:29:22Z   [Warning]   The Function app may be missing the 'Az.Resources' module. If 'Az.Resources' is available on the PowerShell Gallery, add a reference to this module to requirements.psd1. Make sure this module is compatible with PowerShell 7. For more details, see https://aka.ms/functions-powershell-managed-dependency.
             2023-12-20T00:29:22Z   [Warning]   The Function app may be missing the 'SqlServer' module. If 'SqlServer' is available on the PowerShell Gallery, add a reference to this module to requirements.psd1. Make sure this module is compatible with PowerShell 7. For more details, see https://aka.ms/functions-powershell-managed-dependency.
             2023-12-20T00:29:22Z   [Warning]   The Function app may be missing a module containing the 'Connect-AzAccount' command definition. If this command belongs to a module available on the PowerShell Gallery, add a reference to this module to requirements.psd1. Make sure this module is compatible with PowerShell 7. For more details, see https://aka.ms/functions-powershell-managed-dependency. If the module is installed but you are still getting this error, try to import the module explicitly by invoking Import-Module just before the command that produces the error: this will not fix the issue but will expose the root cause.
             2023-12-20T00:29:22Z   [Information]   INFORMATION: PowerShell HTTP trigger function processed a request.
             2023-12-20T00:29:22Z   [Information]   Executed 'Functions.HttpTrigger1' (Succeeded, Id=02995eda-b227-4971-9fd2-2f9b05f951c1, Duration=133457ms)
             2023-12-20T00:29:22Z   [Error]   ERROR: The specified module 'Az.Accounts' was not loaded because no valid module file was found in any module directory.
    
             Exception             : 
                 Type    : System.IO.FileNotFoundException
                 Message : The specified module 'Az.Accounts' was not loaded because no valid module file was found in any module directory.
                 HResult : -2147024894
             TargetObject          : Az.Accounts
             CategoryInfo          : ResourceUnavailable: (Az.Accounts:String) [Import-Module], FileNotFoundException
             FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand
             InvocationInfo        : 
                 MyCommand        : Import-Module
                 ScriptLineNumber : 7
                 OffsetInLine     : 1
                 HistoryId        : 1
                 ScriptName       : C:\home\site\wwwroot\HttpTrigger1\run.ps1
                 Line             : Import-Module Az.Accounts -Force
    
                 PositionMessage  : At C:\home\site\wwwroot\HttpTrigger1\run.ps1:7 char:1
                                    + Import-Module Az.Accounts -Force
                                    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                 PSScriptRoot     : C:\home\site\wwwroot\HttpTrigger1
                 PSCommandPath    : C:\home\site\wwwroot\HttpTrigger1\run.ps1
                 InvocationName   : Import-Module
                 CommandOrigin    : Internal
             ScriptStackTrace      : at <ScriptBlock>, C:\home\site\wwwroot\HttpTrigger1\run.ps1: line 7
             PipelineIterationInfo : 
    
    
    
    
             2023-12-20T00:29:22Z   [Error]   ERROR: The specified module 'Az.Resources' was not loaded because no valid module file was found in any module directory.
    
             Exception             : 
                 Type    : System.IO.FileNotFoundException
                 Message : The specified module 'Az.Resources' was not loaded because no valid module file was found in any module directory.
                 HResult : -2147024894
             TargetObject          : Az.Resources
             CategoryInfo          : ResourceUnavailable: (Az.Resources:String) [Import-Module], FileNotFoundException
             FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand
             InvocationInfo        : 
                 MyCommand        : Import-Module
                 ScriptLineNumber : 8
                 OffsetInLine     : 1
                 HistoryId        : 1
                 ScriptName       : C:\home\site\wwwroot\HttpTrigger1\run.ps1
                 Line             : Import-Module Az.Resources -Force
    
                 PositionMessage  : At C:\home\site\wwwroot\HttpTrigger1\run.ps1:8 char:1
                                    + Import-Module Az.Resources -Force
                                    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                 PSScriptRoot     : C:\home\site\wwwroot\HttpTrigger1
                 PSCommandPath    : C:\home\site\wwwroot\HttpTrigger1\run.ps1
                 InvocationName   : Import-Module
                 CommandOrigin    : Internal
             ScriptStackTrace      : at <ScriptBlock>, C:\home\site\wwwroot\HttpTrigger1\run.ps1: line 8
             PipelineIterationInfo : 
    

2 Comments

Did you enable Managed Identity?
Yes, MI enabled with contributor access on the RG

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.