如何使用ADO YAML管道发布成功并成功地发送Slack消息? 我正在尝试将Slack消息发送到构建后的指定频道,所有分支策略都是成功的,并且所有状态检查都通过Azure Devops Yaml管道传递。但是看来我有几个

问题描述 投票:0回答:1
如果构建失败或任何分支策略失败,请直接消息拉动请求创建者。

如果在拉动请求处于活动状态时将任何新提交都归于分支机构,或者在拉动请求中解决任何注释,则管道将重新运行并遵循同一步骤。

我尝试了什么:

  1. 我尝试了一堆不同的条件组合,但它们没有起作用。
  2. ,例如,无依赖性的平原成功()和失败()或成功('test')作为阶段级别或成功('UnitTest')作为工作级别。
  3. 我还试图拥有阶段来建造和恢复,但这在这一点上不是必需的。 4.在大多数情况下,即使失败了,他们也会发送成功消息,并且失败不会发送直接消息,并且发送的消息不包含任何成功的变量。
  4. 问题:

我找不到适当的条件设置来区分成功和失败。 我找不到Slack用户ID以及其他变量来填充Slack Messages。 slack中的消息格式化正确 只有在所有分支政策通过之后,我也很难作为最后一步 - “至少1个审稿人必须批准”。分支政策是继承的。

添加状态检查条件。
    我也在下面包含了一些参考图像。
  1. trigger: - none # Disable automatic trigger for commits. Trigger only for PRs. resources: repositories: - repository: templates type: git name: Hagerty/azure-pipelines-templates pr: branches: include: - main # Only trigger for PRs targeting 'main' pool: vmImage: 'windows-latest' variables: - group: billing_pr_slack_notification # ADO variable group stages: - stage: BuildAndNotify displayName: 'Billing PR Slack Notifications' # Ensure this stage runs only after all PR policies succeed condition: and(succeeded(), eq(coalesce(variables['System.PullRequest.IsDraft'], false), false), startsWith(variables['Build.SourceBranch'], 'refs/pull/')) jobs: - job: LogVariables displayName: 'Log Pipeline Variables' steps: - script: | echo '=== Debugging Variables ===' echo 'AZURE_DEVOPS_ORG: $(AZURE_DEVOPS_ORG)' echo 'AZURE_DEVOPS_PROJECT: $(AZURE_DEVOPS_PROJECT)' echo 'SLACK_API_URL: $(SLACK_API_URL)' echo 'SLACK_BOT_TOKEN: $(SLACK_BOT_TOKEN)' echo 'SLACK_CHANNEL: $(SLACK_CHANNEL)' echo 'PRODUCT_BILLING_DEV_WEBHOOK_URL: $(PRODUCT_BILLING_DEV_WEBHOOK_URL)' echo 'System.PullRequest.IsDraft: $(System.PullRequest.IsDraft)' echo 'System.PullRequest.SourceBranch: $(System.PullRequest.SourceBranch)' echo 'System.PullRequest.TargetBranch: $(System.PullRequest.TargetBranch)' displayName: 'Output Debugging Variables' - job: FetchSlackUserID displayName: 'Fetch Slack User ID' dependsOn: LogVariables steps: - powershell: | $creatorEmail = $env:BUILD_REQUESTEDFOR if (-not $creatorEmail) { Write-Host "##vso[task.logissue type=error]The Build.RequestedFor email is empty. Cannot proceed to fetch Slack User ID." exit 1 } $slackToken = "$env:SLACK_BOT_TOKEN" $response = Invoke-RestMethod -Uri "https://slack.com/api/users.lookupByEmail?email=$creatorEmail" -Headers @{Authorization="Bearer $slackToken"} if ($response.ok -eq $true -and $response.user.id) { $userId = $response.user.id Write-Host "##vso[task.setvariable variable=userId]$userId" Write-Host "Successfully retrieved Slack User ID: $userId" Write-Host "Debug: Slack User ID is $userId" } else { Write-Host "Defaulting to Slack channel $env:SLACK_CHANNEL." Write-Host "##vso[task.setvariable variable=userId]$env:SLACK_CHANNEL" } displayName: 'Fetch Slack User ID' - job: SlackNotification displayName: 'Send Slack Notifications' dependsOn: FetchSlackUserID steps: # Send a channel notification only on success - powershell: | $webhookUrl = "$env:PRODUCT_BILLING_DEV_WEBHOOK_URL" $createdBy = $env:SYSTEM_PULLREQUEST_CREATEDBY $prTitle = $env:SYSTEM_PULLREQUEST_TITLE $prDescription = $env:SYSTEM_PULLREQUEST_DESCRIPTION $prUrl = $env:SYSTEM_PULLREQUEST_URL # Handle unset variables by providing default values if (-not $createdBy) { $createdBy = "Unknown User" } if (-not $prTitle) { $prTitle = "Untitled PR" } if (-not $prDescription) { $prDescription = "No description provided." } if (-not $prUrl) { $prUrl = "No link available." } $message = @{ text = "<@here> [$createdBy] has created a new Pull Request & is ready for Code Review:\n**Title**: $prTitle\n**Description**: $prDescription\n[View PR]($prUrl)" } | ConvertTo-Json -Depth 10 Invoke-RestMethod -Uri $webhookUrl -Method Post -Body $message -ContentType 'application/json' Write-Host "Slack channel notification sent successfully." displayName: 'Send Slack Notification' condition: and(succeeded(), endsWith(variables['System.PullRequest.TargetBranch'], '/main')) # Send a direct message only on failure - powershell: | $gifUrls = @( "https://media.giphy.com/media/Ju7l5y9osyymQ/giphy.gif", "https://media.giphy.com/media/26AHONQ79FdWZhAI0/giphy.gif", "https://media.giphy.com/media/3o6Zt481isNVuQI1l6/giphy.gif" ) $randomGif = $gifUrls | Get-Random $slackToken = "$env:SLACK_BOT_TOKEN" $userId = "$env:userId" $prTitle = $env:SYSTEM_PULLREQUEST_TITLE $prUrl = $env:SYSTEM_PULLREQUEST_URL # Handle unset variables by providing default values if (-not $prTitle) { $prTitle = "Untitled PR" } if (-not $prUrl) { $prUrl = "No link available." } $message = if ($env:BUILD_STATUS -eq "Failed") { "Your Pull Request **$prTitle** failed to build. Please review your branch.\n[View PR]($prUrl)\n\n![Failure GIF]($randomGif)" } else { "Your Pull Request **$prTitle** failed the following policy check: $env:BUILD_DEFINITIONNAME. Please review your branch.\n[View PR]($prUrl)\n\n![Failure GIF]($randomGif)" } $body = @{ channel = $userId text = $message } | ConvertTo-Json -Depth 10 Invoke-RestMethod -Uri "https://slack.com/api/chat.postMessage" -Method Post -Headers @{Authorization="Bearer $slackToken"} -Body $body Write-Host "Slack DM sent successfully to user $userId." displayName: 'Send Slack DM if Build or Policy Fails' condition: failed()

  1. 对您的管道有一些担忧。
  2. 第一个是对
  3. jobs
  4. 和可变范围的常见误解。 Microsoft Cloud托管代理(Windows-latest
  5. )中的每个作业都在其他代理上运行,因此您在该作业中创建的任何环境变量都无法用于后续作业。工作应该是大型工作单位,您将相关事物分组在一起。在您的情况下,实际上,您在不同的作业中运行了三个类似的活动,除了范围问题外,这些活动还将大大减慢管道的速度,因为系统将花费大量时间分配新代理商。通过多个步骤
单调工作,您会更好,因为您在早期步骤中创建的变量将始终在后续步骤中可用(加上执行时间的较小减少)。

第二个问题与您的状况有关。该函数

succeeded()

BranchPoliciesfailedStatusChecks电流作业的执行。当您写的时候,您在SlackNotificationSlackFormatting作业中的任务中有条件。第一个任务的条件没有效果,因为它是作业中的第一个任务,而第二任务的条件仅在“发送Slack Notification” PowerShell任务失败时执行,这可能不是您'之后 我假设您希望根据构建活动的结果应用成功或失败的条件。您尚未在管道中显示构建活动,但是假设为了清楚起见,您可以通过两个工作来实现所需的效果:

azure-devops azure-pipelines azure-pipelines-yaml
1个回答
0
投票
与您的变量相关:

System_pullrequest_createdby无效。使用failed() System_pullrequest_url无效。使用trigger: none jobs: - job: build steps: ... steps to build are here - job: slacknotify displayName: 'Send Slack Notification' dependsOn: - build # specify a condition that looks at the "build" job's final result condition: | and( in(dependencies.build.result, 'Succeeded', 'Failed'), eq(variables['Build.Reason'],'PullRequest') ) variables: # create a job scoped variable that holds the outcome of the build result buildResult: $[ dependencies.build.result ] steps: - powershell: | ... displayName: Resolve Slack User ID - powershell: | ... displayName: Send Success Message condition: eq(variables['buildResult'], 'Success') - powershell: | ... displayName: Send Failure Message condition: eq(variables['buildResult'], 'Failed')

$(Build.RequestedBy)

构建URL。 System_pullrequest_title和system_pullrequest_description无效。您必须使用REST API获取拉动请求详细信息。

为了确定分支策略完成标准,您必须使用rest api来获取拉动请求以评估已经满足了哪些条件。
lastly,您指定的trigger没有效果。因为您使用的是Azure存储库(分支策略所证明的),所以
PR触发器只能与GitHub或BitbucketCloud
一起使用。该管道只有在分支策略的构建验证中配置在拉动请求时才会触发。
© www.soinside.com 2019 - 2024. All rights reserved.