运行Azure Functions应用程序时出现间歇性错误消息

如何解决运行Azure Functions应用程序时出现间歇性错误消息

我有一个Powershell程序,该程序按计划在Azure Functions应用中运行。它连接到Office 365以下载审核日志,进行一些更改,然后将CSV导出到Azure Data Lake Storage帐户。为避免使用硬编码的凭据,Azure密钥保管库存储机密。我在Azure功能中创建了托管身份以及所需的应用程序设置和指向Azure Key Vault的URL。该代码引用了应用程序机密(APPSETTING),并且似乎运行良好,直到今天我注意到从昨天下午开始,导出的CSV文件为空。

因此,我打开了Function应用程序,单击“手动运行”,可以看到导出了数据的CSV文件。但是,当我查看执行日志时,我发现了这些错误消息,尽管这次不影响执行,却使我怀疑这是否是空CSV文件的问题。该程序现在可以按计划正常运行,并且错误消息似乎是间歇性的。

enter image description here

不确定当它明显能够访问数据源(Office审核日志),导出CSV并将其成功传输到文件目标位置(Azure Data Lake Storage)时,为什么抱怨用户名和密码。

知道发生了什么吗?欢迎任何提示或建议!下面提供的代码。非常感谢!

  # Input bindings are passed in via param block.
    param($Timer)

    # Get the current universal time in the default string format.
    $currentUTCtime = (Get-Date).ToUniversalTime()

    # The 'IsPastDue' property is 'true' when the current function invocation is later than scheduled.
    if ($Timer.IsPastDue) {
        Write-Host "PowerShell timer is running late!"
    }

    # Write an information log with the current time.
    Write-Host "PowerShell timer trigger function ran! TIME: $currentUTCtime"

    <# 
    Title: Power BI Audit Logging 
    Client: 

    Description: Connects to Azure audit logs using admin credentials (secrets via Azure Key Vault). Opens a session to iterate through the Audit Log ($currentrResults) and aggregate 
    the logs into a single object ($aggregateResults). A for-each loop then iterates through the $aggregateResults and assigns each data piece (datum)
    to a PowerShell object to which properties are added to hold the audit data. A CSV file is created and exported,and then transferred to a Data Lake storage account (using SAS secret via Azure Key Vault). 

    Last Revision: 06/09/2020 #>

    Set-ExecutionPolicy RemoteSigned
    Set-Item ENV:\SuppressAzurePowerShellBreakingChangeWarnings "true"

    # Better for scheduled jobs
    $uSecret = $ENV:APPSETTING_SecretUsername
    $pSecret = $ENV:APPSETTING_SecretPassword 
    $sasSecret = $ENV:APPSETTING_SecretSAS

    $securePassword = ConvertTo-SecureString -String $pSecret -AsPlainText -Force

    $UserCredential = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $uSecret,$securePassword

    # This will prompt the user for credential (optional)
    # $UserCredential = Get-Credential

    $session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
    Import-PSSession $session

    $startDate=(get-date).AddDays(-10)
    $endDate=(get-date)
    $scriptStart=(get-date)

    $sessionName = (get-date -Format 'u')+'pbiauditlog'
    # Reset user audit accumulator
    $aggregateResults = @()
    $i = 0 # Loop counter
    Do { 
        $currentResults = Search-UnifiedAuditLog -StartDate $startDate -EndDate $enddate -SessionId $sessionName -SessionCommand ReturnLargeSet -ResultSize 1000 -RecordType PowerBIAudit
        if ($currentResults.Count -gt 0) {
            Write-Host ("Finished {3} search #{1},{2} records: {0} min" -f [math]::Round((New-TimeSpan -Start $scriptStart).TotalMinutes,4),$i,$currentResults.Count,$user.UserPrincipalName )
            # Accumulate the data.
            $aggregateResults += $currentResults
            # No need to do another query if the # records returned <1000 - should save around 5-10 seconds per user.
            if ($currentResults.Count -lt 1000) {
                $currentResults = @()
            } else {
                $i++
            }
        }
    } Until ($currentResults.Count -eq 0) # End of Session Search Loop.

    $data=@()

    foreach ($auditlogitem in $aggregateResults) {
        $datum = New-Object -TypeName PSObject  
        $d = ConvertFrom-json $auditlogitem.AuditData
        $datum | Add-Member -MemberType NoteProperty -Name Id -Value $d.Id
        $datum | Add-Member -MemberType NoteProperty -Name CreationTDateTime -Value $d.CreationDate
        $datum | Add-Member -MemberType NoteProperty -Name CreationTime -Value $d.CreationTime
        $datum | Add-Member -MemberType NoteProperty -Name RecordType -Value $d.RecordType
        $datum | Add-Member -MemberType NoteProperty -Name Operation -Value $d.Operation
        $datum | Add-Member -MemberType NoteProperty -Name OrganizationId -Value $d.OrganizationId
        $datum | Add-Member -MemberType NoteProperty -Name UserType -Value $d.UserType
        $datum | Add-Member -MemberType NoteProperty -Name UserKey -Value $d.UserKey
        $datum | Add-Member -MemberType NoteProperty -Name Workload -Value $d.Workload
        $datum | Add-Member -MemberType NoteProperty -Name UserId -Value $d.UserId
        $datum | Add-Member -MemberType NoteProperty -Name ClientIPAddress -Value $d.ClientIPAddress
        $datum | Add-Member -MemberType NoteProperty -Name UserAgent -Value $d.UserAgent
        $datum | Add-Member -MemberType NoteProperty -Name Activity -Value $d.Activity
        $datum | Add-Member -MemberType NoteProperty -Name ItemName -Value $d.ItemName
        $datum | Add-Member -MemberType NoteProperty -Name WorkSpaceName -Value $d.WorkSpaceName
        $datum | Add-Member -MemberType NoteProperty -Name DashboardName -Value $d.DashboardName
        $datum | Add-Member -MemberType NoteProperty -Name DatasetName -Value $d.DatasetName
        $datum | Add-Member -MemberType NoteProperty -Name ReportName -Value $d.ReportName
        $datum | Add-Member -MemberType NoteProperty -Name WorkspaceId -Value $d.WorkspaceId
        $datum | Add-Member -MemberType NoteProperty -Name ObjectId -Value $d.ObjectId
        $datum | Add-Member -MemberType NoteProperty -Name DashboardId -Value $d.DashboardId
        $datum | Add-Member -MemberType NoteProperty -Name DatasetId -Value $d.DatasetId
        $datum | Add-Member -MemberType NoteProperty -Name ReportId -Value $d.ReportId
        $datum | Add-Member -MemberType NoteProperty -Name OrgAppPermission -Value $d.OrgAppPermission
            
        # Option to include the below JSON column however for large amounts of data it may be difficult for PBI to parse
        $datum | Add-Member -MemberType NoteProperty -Name Datasets -Value (ConvertTo-Json $d.Datasets)
        
        # Below is a simple PowerShell statement to grab one of the entries and place in the DatasetName if any exist
        foreach ($dataset in $d.datasets) {
            $datum.DatasetName = $dataset.DatasetName
            $datum.DatasetId = $dataset.DatasetId
        }
        $data+=$datum
    }

    $dateTimestring = $startDate.ToString("yyyyMMdd") + "_" + (Get-Date -Format "yyyyMMdd") + "_" + (Get-Date -Format "HHmm")
    $fileName = ($dateTimestring + ".csv")
    Write-Host ("Writing to file {0}" -f $fileName) 
    $filePath = "$Env:temp/" + $fileName
    $data | Export-csv -Path $filePath

    # File transfer to Azure storage account 
    Get-AzContext #Connect-AzAccount -Credential $UserCredential
    Get-AzVM -ResourceGroupName "Audit" -status
    $Context = New-AzStorageContext -StorageAccountName "auditingstorage" -StorageAccountKey $sasSecret
    Set-AzStorageBlobContent -Force -Context $Context -Container "auditlogs" -File $filePath -Blob $filename 

    # Close PowerShell session
    Remove-PSSession -Id $Session.Id

解决方法

您的错误状态

错误:Connect-AzAccount:用户名和密码验证不正确 在PowerShell Core中受支持。请使用设备代码身份验证 用于交互式登录,或用于脚本的服务主体身份验证 登录。

问题来自在Powershell Core中使用凭据身份验证方案

Connect-AzAccount -Credential $UserCredential

相反,在您的应用中,启用系统托管身份,并授予其访问所需内容的权限。

您可以通过以下方式执行此操作:进入 Identity (身份)窗格,然后在分配的系统中将状态设置为打开 >标签。

从此处,通过 Azure角色分配按钮添加所需的访问权限。

完成此操作后,您无需使用Connect-AzAccount,您的应用程序将在运行时自动连接到托管身份。之后,您可以使用 Identity 窗格中的对象ID Azure Active Directory /应用程序注册中找到它,并为其分配其他 API 访问(如果需要)。

附加说明 您可以始终将 Connect-AzAccount 与服务主体帐户一起使用,但是除非您有此要求,否则我将采用 Managed Identity 路线。

参考

How to use managed Identities for App Service and Azure Functions

Create an Azure service principal with Azure Powershell

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-