运行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 @R_847_4045@ion 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