【Azure 应用服务】Azure Function App 执行PowerShell指令[Get-Azsubscription -TenantId cxt]错误

简介: 【Azure 应用服务】Azure Function App 执行PowerShell指令[Get-Azsubscription -TenantId cxt]错误

问题描述

使用PowerShell脚本执行获取Azure订阅列表的指令(Get-Azsubscription -TenantId tenantID−DefaultProfilecxt)。在本地调试后,指令成功运行。

但是当指令并运行在Azure Function时,则出现了异常:详细的异常信息为

完成的错误信息为: "Error getting value from 'Tags' on 'Microsoft.Azure.Commands.Profile.Models.PSAzureSubscription'."

Microsoft.Azure.WebJobs.Script.Workers.Rpc.RpcException : Result: ERROR: Error getting value from 'Tags' on 'Microsoft.Azure.Commands.Profile.Models.PSAzureSubscription'.
Exception             : 
    Type           : Newtonsoft.Json.JsonSerializationException
    TargetSite     : 
        Name          : GetValue
        DeclaringType : Newtonsoft.Json.Serialization.ExpressionValueProvider
        MemberType    : Method
        Module        : Newtonsoft.Json.dll
    StackTrace     : 
   at Newtonsoft.Json.Serialization.ExpressionValueProvider.GetValue(Object target)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues(JsonWriter writer, Object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, JsonContract& memberContract, Object& memberValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)
   at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)
   at Newtonsoft.Json.JsonSerializer.Serialize(JsonWriter jsonWriter, Object value, Type objectType)
   at Newtonsoft.Json.JsonConvert.SerializeObjectInternal(Object value, Type type, JsonSerializer jsonSerializer)
   at Newtonsoft.Json.JsonConvert.SerializeObject(Object value, Type type, Formatting formatting, JsonSerializerSettings settings)
   at Newtonsoft.Json.JsonConvert.SerializeObject(Object value, Formatting formatting, JsonConverter[] converters)
   at Microsoft.Azure.Commands.Common.Authentication.Models.AzureRmProfile.ToString(Boolean serializeCache)
   at Microsoft.Azure.Commands.Common.Authentication.Models.AzureRmProfile.ToString()
   at System.Management.Automation.ParameterBinderBase.CoerceTypeAsNeeded(CommandParameterInternal argument, String parameterName, Type toType, ParameterCollectionTypeInformation collectionTypeInfo, Object currentValue)
   at System.Management.Automation.ParameterBinderBase.BindParameter(CommandParameterInternal parameter, CompiledCommandParameter parameterMetadata, ParameterBindingFlags flags)
   at System.Management.Automation.CmdletParameterBinderController.BindParameter(CommandParameterInternal argument, MergedCompiledCommandParameter parameter, ParameterBindingFlags flags)
   at System.Management.Automation.CmdletParameterBinderController.BindParameter(UInt32 parameterSets, CommandParameterInternal argument, MergedCompiledCommandParameter parameter, ParameterBindingFlags flags)
   at System.Management.Automation.CmdletParameterBinderController.BindParameters(UInt32 parameterSets, Collection`1 arguments)
   at System.Management.Automation.CmdletParameterBinderController.BindCommandLineParametersNoValidation(Collection`1 arguments)
   at System.Management.Automation.CmdletParameterBinderController.BindCommandLineParameters(Collection`1 arguments)
   at System.Management.Automation.CommandProcessor.BindCommandLineParameters()
   at System.Management.Automation.CommandProcessor.Prepare(IDictionary psDefaultParameterValues)
   at System.Management.Automation.CommandProcessorBase.DoPrepare(IDictionary psDefaultParameterValues)
   at System.Management.Automation.Internal.PipelineProcessor.Start(Boolean incomingStream)
   at System.Management.Automation.Internal.PipelineProcessor.SynchronousExecuteEnumerate(Object input)
   at System.Management.Automation.PipelineOps.InvokePipeline(Object input, Boolean ignoreInput, CommandParameterInternal[][] pipeElements, CommandBaseAst[] pipeElementAsts, CommandRedirection[][] commandRedirections, FunctionContext funcContext)
   at System.Management.Automation.Interpreter.ActionCallInstruction`6.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
    Message        : Error getting value from 'Tags' on 'Microsoft.Azure.Commands.Profile.Models.PSAzureSubscription'.
    Data           : System.Collections.ListDictionaryInternal
    InnerException : 
        Type       : System.ArgumentNullException
        Message    : Value cannot be null. (Parameter 'value')
        ParamName  : value
        TargetSite : 
            Name          : ArgumentNotNull
            DeclaringType : Newtonsoft.Json.Utilities.ValidationUtils, Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed
            MemberType    : Method
            Module        : Newtonsoft.Json.dll
        StackTrace : 
   at Newtonsoft.Json.Utilities.ValidationUtils.ArgumentNotNull(Object value, String parameterName)
   at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
   at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)
   at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value)
   at Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureSubscriptionExtensions.GetTags(IAzureSubscription subscription)
   at lambda_method(Closure , Object )
   at Newtonsoft.Json.Serialization.ExpressionValueProvider.GetValue(Object target)
        Source     : Newtonsoft.Json
        HResult    : -2147467261
    Source         : Newtonsoft.Json
    HResult        : -2146233088
CategoryInfo          : OperationStopped: (:) [], JsonSerializationException
FullyQualifiedErrorId : Newtonsoft.Json.JsonSerializationException
InvocationInfo        : 
    ScriptLineNumber : 26
    OffsetInLine     : 1
    HistoryId        : -1
    ScriptName       : D:\home\site\wwwroot\HttpTrigger1\run.ps1
    Line             : $subs = Get-Azsubscription -TenantId $tenantID -DefaultProfile $cxt
                       
    PositionMessage  : At D:\home\site\wwwroot\HttpTrigger1\run.ps1:26 char:1
                       + $subs = Get-Azsubscription -TenantId $tenantID -DefaultProfile $cxt
                       + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    PSScriptRoot     : D:\home\site\wwwroot\HttpTrigger1
    PSCommandPath    : D:\home\site\wwwroot\HttpTrigger1\run.ps1
    CommandOrigin    : Internal
ScriptStackTrace      : at <ScriptBlock>, D:\home\site\wwwroot\HttpTrigger1\run.ps1: line 26

 

问题分析及临时解决方案

对比以上本地可以成功运行,而在Azure Function中确出现JSON格式解析错误,所以排查PowerShell脚本错误问题。 那么就定位在运行脚本的环境问题。

第一步:排查PowerShell版本,及az 模块的版本

通过 $PSVersionTable 打出PowerShell版本,通过 Get-InstalledModule -name az 和 Get-InstalledModule -name az.* 打印出当前环境的版本号。

 

经过对比,发现本地VM与Azure Function中Powershell和az 模块的版本都不同.  

第二步:寻找临时的解决方案

由于Azure Function中PowerShell的版本从平台级别无法更改(可以修改PS脚本中所使用的az模块版本,修改方式见附件一)。所以主要的寻找发向为:基于现在的版本,从Get-Azsubscription指令本身来寻找Workaround呢?查看Get-Azsubscription指令,发现它使用的是当前登录用户的权限去获取所有的订阅号,指定TenantID是表明只获取当前TenantID下的所有订阅号。而参数DefaultProfile也是只携带用户认证信息,与当前登录的用户所有的认证信息重复。

Get-AzSubscription

Get subscriptions that the current account can access

-TenantId

Specifies the ID of the tenant that contains subscriptions to get

-DefaultProfile

The credentials, tenant and subscription used for communication with azure

如果不添加-DefaultProfile参数,是否同样由异常呢? 经过验证执行成功并返回结果正确。所以作为Workaround的代码为:

# Write to the Azure Functions log stream.
Write-Host "PowerShell HTTP trigger function processed a request."
$User = "XXXXXXXXXXXXXxxxxxxxx"
$PWord = ConvertTo-SecureString -String "XXXXXXXXXXXXXxxxxxxxx" -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential($User, $PWord)
Connect-AzAccount -Environment AzureChinaCloud -Credential $Credential
Write-Host "login successfully"
$tenantID = "xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
$cxt = Set-AzContext -Tenant $tenantID
write-host $cxt
write-host "no defaultprofile"
Write-Host "Get-Azsubscription -TenantId $tenantID"
#$subs = Get-Azsubscription -TenantId $tenantID -DefaultProfile $cxt
Get-Azsubscription -TenantId $tenantID
write-host "========================="
write-host $subs

附件一:在Azure Funciton中修改az的版本号为5.2.0, 问题也得到解决。

在Azure Function 门户页面,点击“App Service Editor (Preview)” 目录,进入Editor页面,在文件requirements.psd1文件中,修改az的版本号为5.2.0. 保存后,回到Azure Function页面。重启Function. 修改页面如下:

 

结论: 解决办法有两种

  1. 修改az的版本号为5.2.0,修改办法见附件一
  2. 修改Get-Azsubscription指令,去掉参数 -DefaultProfile $cxt

 

 

参考资料

Get-AzSubscriptionhttps://docs.microsoft.com/en-us/powershell/module/az.accounts/get-azsubscription?view=azps-6.2.0

相关文章
|
12天前
|
C# Windows
【Azure App Service】在App Service for Windows上验证能占用的内存最大值
根据以上测验,当使用App Service内存没有达到预期的值,且应用异常日志出现OutOfMemory时,就需要检查Platform的设置是否位64bit。
37 11
|
13天前
|
JavaScript C++ 容器
【Azure Bot Service】部署NodeJS ChatBot代码到App Service中无法自动启动
2024-11-12T12:22:40.366223350Z Error: Cannot find module 'dotenv' 2024-11-12T12:40:12.538120729Z Error: Cannot find module 'restify' 2024-11-12T12:48:13.348529900Z Error: Cannot find module 'lodash'
37 11
|
7天前
|
缓存 容器 Perl
【Azure Container App】Container Apps 设置延迟删除 (terminationGracePeriodSeconds) 的解释
terminationGracePeriodSeconds : 这个参数的定义是从pod收到terminated signal到最终shutdown的最大时间,这段时间是给pod中的application 缓冲时间用来处理链接关闭,应用清理缓存的;并不是从idel 到 pod被shutdown之间的时间;且是最大时间,意味着如果application 已经gracefully shutdown,POD可能被提前terminated.
|
11天前
|
开发框架 监控 .NET
【Azure App Service】部署在App Service上的.NET应用内存消耗不能超过2GB的情况分析
x64 dotnet runtime is not installed on the app service by default. Since we had the app service running in x64, it was proxying the request to a 32 bit dotnet process which was throwing an OutOfMemoryException with requests >100MB. It worked on the IaaS servers because we had the x64 runtime install
|
10天前
|
Java 开发工具 Windows
【Azure App Service】在App Service中调用Stroage SDK上传文件时遇见 System.OutOfMemoryException
System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
|
10天前
|
安全 Apache 开发工具
【Azure App Service】在App Service上关于OpenSSH的CVE2024-6387漏洞解答
CVE2024-6387 是远程访问漏洞,攻击者通过不安全的OpenSSh版本可以进行远程代码执行。CVE-2024-6387漏洞攻击仅应用于OpenSSH服务器,而App Service Runtime中并未使用OpenSSH,不会被远程方式攻击,所以OpenSSH并不会对应用造成安全风险。同时,如果App Service的系统为Windows,不会受远程漏洞影响!
|
20天前
|
C#
【Azure App Service】使用Microsoft.Office.Interop.Word来操作Word文档,部署到App Service后报错COMException
System.Runtime.InteropServices.COMException (0x80040154): Retrieving the COM class factory for component with CLSID {000209FF-0000-0000-C000-000000000046} failed due to the following error: 80040154 Class not registered (0x80040154 (REGDB_E_CLASSNOTREG)).
|
21天前
【Azure App Service】PowerShell脚本批量添加IP地址到Web App允许访问IP列表中
Web App取消公网访问后,只允许特定IP能访问Web App。需要写一下段PowerShell脚本,批量添加IP到Web App的允许访问IP列表里!
|
27天前
|
机器人 Shell Linux
【Azure Bot Service】部署Python ChatBot代码到App Service中
本文介绍了使用Python编写的ChatBot在部署到Azure App Service时遇到的问题及解决方案。主要问题是应用启动失败,错误信息为“Failed to find attribute &#39;app&#39; in &#39;app&#39;”。解决步骤包括:1) 修改`app.py`文件,添加`init_func`函数;2) 配置`config.py`,添加与Azure Bot Service认证相关的配置项;3) 设置App Service的启动命令为`python3 -m aiohttp.web -H 0.0.0.0 -P 8000 app:init_func`。
|
1月前
|
Linux Python
【Azure Function】Python Function部署到Azure后报错No module named '_cffi_backend'
ERROR: Error: No module named '_cffi_backend', Cannot find module. Please check the requirements.txt file for the missing module.

热门文章

最新文章

下一篇
无影云桌面