In Azure, I have a Function App that has System Identity configured to connect to a resource group. The stack is PowerShell. The function works well in Azure.
But, when I try to debug that PowerShell function locally in Visual Studio Code, I get a weird error "You cannot call a method on a null-valued expression". The function fails on the line that would be using System Identity permissions in Azure.
If I add "Connect-AzAccount" to the beginning of the function and authenticate interactively during the local debug session, all works fine -- no error.
My question is what's the proper workflow for when one needs to debug a PowerShell function that relies on System Identity in Azure? Is there any way from inside the function to call Connect-AzAccount only if System Identity is not present?
"You cannot call a method on a null-valued expression". The function fails on the line that would be using System Identity permissions in Azure.
For this error, I have changed profile.ps1 file code in the Azure Function Project for connecting to the Azure Account in terms of System Assigned Managed Identity Context given in this MS Doc:
if ($env:MSI_SECRET) {
Disable-AzContextAutosave -Scope Process | Out-Null
# Connect-AzAccount -Identity
$AzureIdentityContext = (Connect-AzAccount -Identity).context
$AzureIdentityContext = Set-AzContext -SubscriptionName $AzureIdentityContext.Subscription -DefaultProfile $AzureIdentityContext
}
For the debugging of Azure PowerShell Functions locally in VS Code, I'm getting the below error:
Running without debugging is working good with the Connect Azure Account as Identity
Code:
Also, I have found the VS Code having issues in debugging the Azure PowerShell Function, tested in one of my workarounds June 2022 - SO - #72634272 and raised the ticket in GitHub which is still in Open State and marked as bug and investigation in process..
References: GitHub Issue #3223 of VS Code - Azure Functions Repository.
Not Sure it is the fix or temporary workaround, but I have followed a solution given by @tanieee28 in the similar GitHub issue #5279
i.e., changed the launch.json
and tasks.json
accordingly given in the above GitHub issue:
launch.json:
{
"version": "0.2.0",
"configurations": [
{
"name": "Attach to PowerShell Functions",
"type": "PowerShell",
"request": "attach",
"customPipeName": "AzureFunctionsPSWorker",
"runspaceId": 1,
"processId": "${command:azureFunctions.pickProcess}",
"preLaunchTask": "func start"
}
]
}
tasks.json:
{
"version": "2.0.0",
"tasks": [
{
"label": "func start",
"type": "shell",
"command": "func start",
"problemMatcher": "$func-powershell-watch",
"isBackground": true
}
]
}