【Azure Function App】PowerShell Function 使用 Connect-MgGraph 偶发无法连接 ERROR: Failed to connect to Microsoft Graph with Managed Identity.
问题描述
Azure Function(PowerShell) 在未改变的情况下,偶发无法通过 Managed Identity 连接 Microsoft Graph。
错误信息:
ERROR: Failed to connect to Microsoft Graph with Managed Identity.
Error: Could not acquire access to file at '.mg\mg.context.json'. Please ensure you have access to this file and try again in a few minutes..Exception : Type : Microsoft.PowerShell.Commands.WriteErrorException Message : Failed to connect to Microsoft Graph with Managed Identity.
Error: Could not acquire access to file at '.mg\mg.context.json'. Please ensure you have access to this file and try again in a few minutes.. HResult : -2146233087CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Connect-GraphWithManagedIdentity
报错关键点为:
Failed to connect to Microsoft Graph with Managed IdentityCould not acquire access to file at '.mg\mg.context.json'
问题解答
这类“间歇性无法访问
.mg\mg.context.json”的问题,本质上是 运行时环境对用户配置文件(User Profile)加载/可用性导致的副作用:Microsoft Graph PowerShell(或封装函数 Connect-GraphWithManagedIdentity)在某些流程中会依赖本地的上下文/缓存文件目录(例如 .mg 目录下的 mg.context.json)。当 Azure Functions 的宿主进程未加载用户 profile,或对 profile 目录/缓存目录的访问在特定实例生命周期中不稳定时,就可能出现“偶发读写失败”的现象。
问题的解决办法是: 在 Function App 的应用设置中添加
WEBSITE_LOAD_USER_PROFILE=1,让运行时在启动时加载用户 profile,从而使相关上下文/缓存路径的访问更稳定。参考资料
当在复杂的环境中面临问题,格物之道需:浊而静之徐清,安以动之徐生。 云中,恰是如此!

浙公网安备 33010602011771号