如何从Azure DevOps提取触发流水线的Webhook名称?
解决Azure DevOps流水线识别Webhook触发源的问题
问题根源
你当前的配置有两个核心错误:
- 数组索引错误:
resources.webhooks是0起始的数组,且只有触发当前流水线的Webhook会被包含在数组中,你写的[2]完全超出索引范围,自然拿不到值。 - 用错变量:Azure DevOps提供了专门的内置变量
resources.triggeringWebhook.name,直接就能获取触发流水线的Webhook名称,不需要自己解析JSON参数。
另外你之前尝试的sed命令存在语法错误(末尾缺少闭合的'),且完全没必要用这种方式。
修正后的流水线配置
resources: webhooks: - webhook: webhook1 connection: ServiceConnection1 - webhook: webhook2 connection: ServiceConnection2 trigger: branches: include: - main stages: - stage: Stage1 condition: eq(variables['resources.triggeringWebhook.name'], 'webhook1') jobs: - job: Job1 steps: - script: echo "This stage is triggered by webhook1" - stage: Stage2 condition: eq(variables['resources.triggeringWebhook.name'], 'webhook2') jobs: - job: Job1 steps: - script: echo "This stage is triggered by webhook2"
额外说明
- 如果需要验证Webhook的其他信息,可以用
resources.triggeringWebhook.payload获取完整的Webhook请求体,比如在步骤里输出:echo ${{ convertToJson(resources.triggeringWebhook.payload) }} - 当流水线被分支提交触发时,
resources.triggeringWebhook变量会不存在,此时两个stage的condition都会不满足,流水线会直接跳过所有stage。如果需要处理这种情况,可以给stage加额外的condition判断,比如:condition: or(eq(variables['resources.triggeringWebhook.name'], 'webhook1'), ne(variables['Build.Reason'], 'ResourceTrigger'))
内容的提问来源于stack exchange,提问作者rewa
相关产品推荐
相关产品推荐

