如果在拉动请求处于活动状态时将任何新提交都归于分支机构,或者在拉动请求中解决任何注释,则管道将重新运行并遵循同一步骤。
我尝试了什么:
我找不到适当的条件设置来区分成功和失败。 我找不到Slack用户ID以及其他变量来填充Slack Messages。 slack中的消息格式化正确 只有在所有分支政策通过之后,我也很难作为最后一步 - “至少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"
} else {
"Your Pull Request **$prTitle** failed the following policy check: $env:BUILD_DEFINITIONNAME. Please review your branch.\n[View PR]($prUrl)\n\n"
}
$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()
第二个问题与您的状况有关。该函数
succeeded()
和failed
指电流作业的执行。当您写的时候,您在SlackNotification
作业中的任务中有条件。第一个任务的条件没有效果,因为它是作业中的第一个任务,而第二任务的条件仅在“发送Slack Notification” PowerShell任务失败时执行,这可能不是您'之后
我假设您希望根据构建活动的结果应用成功或失败的条件。您尚未在管道中显示构建活动,但是假设为了清楚起见,您可以通过两个工作来实现所需的效果:
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一起使用。该管道只有在分支策略的构建验证中配置在拉动请求时才会触发。