GitHub Action如何配置依赖任一条件触发作业的通知任务
解决方案
核心是给notify-slack作业添加自定义if触发条件,同时利用GitHub Actions内置的作业状态检查函数、needs上下文获取上游作业的执行结果即可实现需求,具体规则如下:
- 保留
needs: [test-1, test-2]配置,确保所有上游作业处理完成后才执行通知 - 添加
if规则,只要两个测试作业不全部为跳过状态就触发通知作业 - 补充状态判断逻辑,确保通知颜色能正确匹配实际执行的测试作业结果
修改后的完整工作流代码
name: APP Build on: push: branches: - feature/test jobs: test-1: runs-on: ubuntu-latest if: ${{ github.event_name == 'push' && contains( github.event.head_commit.message, 'test1') }} steps: - name: test-fail run: echo "test1" test-2: runs-on: ubuntu-latest if: ${{ github.event_name == 'push' && contains( github.event.head_commit.message, 'test2') }} steps: - name: test-fail run: echo "test1" notify-slack: name: Slack Notification runs-on: ubuntu-latest needs: [test-1, test-2] # 核心触发条件:两个测试作业不全部跳过就执行 if: | always() && (needs.test-1.result != 'skipped' || needs.test-2.result != 'skipped') steps: - name: Slack Notification uses: rtCamp/action-slack-notify@v2.2.0 env: SLACK_CHANNEL: alert # 颜色逻辑:只要有任意一个测试作业失败就显示危险色,全部成功显示成功色 SLACK_COLOR: | ${{ (needs.test-1.result == 'failure' || needs.test-2.result == 'failure') ? 'danger' : 'good' }}
配置说明
always():强制跳过GitHub Actions默认的上游作业状态检查,否则只要有一个上游作业跳过/失败,当前作业默认就会被跳过needs.<作业名>.result:可以获取对应上游作业的执行结果,可选值为success/failure/skipped/cancelled- 触发条件的或逻辑保证只要有任意一个测试作业实际执行了,通知作业就会运行,只有两个测试作业都被跳过时通知才会跳过
- 颜色判断逻辑会自动忽略跳过的作业,只统计实际运行的测试作业的最终状态
内容的提问来源于stack exchange,提问作者Vikas Rathore
相关产品推荐
相关产品推荐

