You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何查看Azure Deployment Scripts中PowerShell脚本的日志?

问题描述

我通过ARM模板执行包含Write-Host语句的PowerShell脚本创建角色分配,需要查看脚本的stdout/stderr输出,但遇到了部署失败且日志面板无内容的问题。

我的ARM模板配置

@description('Add role assignments to any resource using a PowerShell script.')
resource addRoleAssignments 'Microsoft.Resources/deploymentScripts@2023-08-01' = {
  // Disable the rule because the resource name is dynamic and cannot be stable
  #disable-next-line use-stable-resource-identifiers
  name: 'AddRoleAssignments'
  location: resourceGroup().location
  kind: 'AzurePowerShell'
  properties: {
    azPowerShellVersion: '13.2'
    environmentVariables: []
    scriptContent: loadTextContent('AddRoleAssignments.ps1')
    arguments: '-SubscriptionId ${subscriptionId} -ResourceGroup ${resourceGroupName} -RoleAssignmentsBase64 "${allRoleAssignmentsEncoded}"'
    cleanupPreference: 'OnSuccess'
    retentionInterval: 'P1D'
    // Deployment scripts are idempotent, so we can use utcnow on Tag to force an update
    forceUpdateTag: 'Run-${timestamp}'
  }
}

@description('Output all role assignments.')
output allRoleAssignments array = allRoleAssignments

@description('Output the number of successful role assignments.')
output successCount int = addRoleAssignments.properties.outputs.success

@description('Output the number of failed role assignments.')
output failsCount int = addRoleAssignments.properties.outputs.fails

@description('Output the number of skipped role assignments.')
output skippingCount int = addRoleAssignments.properties.outputs.skipping

尝试添加日志资源后的错误

我参考示例添加了以下日志资源定义:

@description('Logs from the deployment script.')
resource logs 'Microsoft.Resources/deploymentScripts/logs@2023-08-01' existing = {
  parent: addRoleAssignments
  name: 'default'
}

@description('The logs written by the script')
output logs array = split(logs.properties.log, '\n')

但部署失败,错误信息如下:

{"status":"Failed","error":{"code":"DeploymentFailed","target":"/subscriptions/1111-11111-1111-1111-111/resourceGroups/wcx-us-gmath/providers/Microsoft.Resources/deployments/roleAssignments.deploymentTemplate","message":"At least one resource deployment operation failed. Please list deployment operations for details.","details":[{"code":"ResourceDeploymentFailure","target":"/subscriptions/17581539-6d93-45c3-87f5-d49bc0553c4b/resourceGroups/wcx-us-gmath/providers/Microsoft.Resources/deploymentScripts/AddRoleAssignments","message":"The resource write operation failed to complete successfully, because it reached terminal provisioning state 'failed'.","details":[{"code":"DeploymentScriptOperationFailed","message":"Encountered an internal server error. The tracking activity id is '054a7492-0e0f-4886-bf9b-4e9c90713d46', correlation id is 'bbbf4437-7478-40a9-94c8-d35c78441e62'."}]}]}}

同时日志面板中看不到任何内容:
日志面板无内容

PowerShell脚本片段

param (
    [string]$SubscriptionId,
    [string]$ResourceGroup,
    [string]$RoleAssignmentsJson
)

# Convert JSON string to PowerShell object
try {
    $decodedJson = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($RoleAssignmentsBase64))        
    $roleAssignments = $decodedJson | ConvertFrom-Json -ErrorAction Stop
    Write-Host "📄 Decoded and parsed $($roleAssignments.Count) role assignments from JSON input."
} catch {
    Write-Error "❌ Failed to parse role assignments JSON input. Error: $_"
    exit 1
}

# Count to be used for logging
$successCount = 0
$failCount = 0
$skippingCount = 0

foreach ($assignment in $roleAssignments) {
    $assigneeName = $assignment.assigneeName
    $resourceName = $assignment.resourceName.ToLower()
    $provider = $assignment.provider.ToLower()
    $roles = $assignment.roles

    ...
}

Write-Host "📊 Role assignments completed. Success: $successCount, Failed: $failCount"
$DeploymentScriptOutputs = @{}
$DeploymentScriptOutputs['success'] = $successCount
$DeploymentScriptOutputs['fails'] = $failCount
$DeploymentScriptOutputs['skipping'] = $skippingCount

解决方案

1. 修复日志资源引用问题

不要用existing关键字引用日志资源,日志是部署脚本资源的内置属性,直接通过部署脚本对象获取即可。修改输出部分:

@description('The logs written by the script')
output logs array = split(addRoleAssignments.properties.log, '\n')

删除单独定义的logs资源,避免因引用未创建的资源导致部署失败。

2. 修正PowerShell脚本参数不匹配问题

脚本参数定义的是$RoleAssignmentsJson,但代码中使用的是$RoleAssignmentsBase64,这会直接导致脚本执行报错,修正参数名:

param (
    [string]$SubscriptionId,
    [string]$ResourceGroup,
    [string]$RoleAssignmentsBase64  # 与ARM模板传递的参数名保持一致
)

这是导致部署失败的核心原因之一。

3. 调整资源清理策略确保日志留存

当前cleanupPreference设置为OnSuccess,成功后会自动清理资源(包括日志)。先改为Always,确保无论执行结果如何,资源都不会被立即清理:

cleanupPreference: 'Always'

问题排查完成后再改回OnSuccess。

4. 直接在门户查看日志

如果ARM输出仍无法获取日志,可直接在Azure门户操作:

  • 进入目标资源组,找到名为AddRoleAssignments的部署脚本资源
  • 进入该资源的「日志」页面,查看脚本执行的详细输出

内容的提问来源于stack exchange,提问作者Guilherme Matheus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 15:55:20