Conditional Job and Step#

有的 Job 或者 Step 你不是什么时候都想执行的. 例如你的 Job 种有一步是只有 Windows 机器上需要做的, 这时候你就可以用 if 语法进行条件判断, 只有条件判断返回 True 才能执行. 并且这个条件判断是可以用 ||, && 来进行组合的.

Sample Workflow Definition#

 1# ------------------------------------------------------------------------------
 2# Demonstrate how to run a job and step conditionally
 3#
 4# Reference:
 5#
 6# - job.<job_id>.if: https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idif
 7# - jobs.<job_id>.steps[*].if: https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsif
 8# - Logical operators: https://docs.github.com/en/actions/learn-github-actions/expressions#operators
 9# - Functions: https://docs.github.com/en/actions/learn-github-actions/expressions#functions
10# - Context Availability: https://docs.github.com/en/actions/learn-github-actions/contexts#context-availability
11# ------------------------------------------------------------------------------
12name: 01_06_conditional_job_and_step
13on:
14  workflow_dispatch:
15    inputs:
16      job_type:
17        description: 'job type'
18        required: true
19        default: 'build'
20        type: choice
21        options:
22          - build
23          - test
24
25jobs:
26  build_job:
27    # note that env context is not available in jobs.<job_id>.if
28    # so we have to use workflow_dispatch.inputs
29    if: ${{ inputs.JOB_TYPE == 'build' }}
30    runs-on: ubuntu-latest
31    env:
32      TASK_ID: 1
33    steps:
34      - name: build 1
35        if: ${{ env.TASK_ID == '1' }} # note that env context is available in steps.<step_id>.if
36        run: echo building 1
37      - name: build 2
38        if: ${{ env.TASK_ID == '2' }}
39        run: echo building 2
40  test_job:
41    if: ${{ inputs.JOB_TYPE == 'test' }}
42    runs-on: ubuntu-latest
43    env:
44      TASK_ID: 1
45    steps:
46      - name: test 1
47        if: ${{ env.TASK_ID == '1' }}
48        run: echo testing 1
49      - name: test 2
50        if: ${{ env.TASK_ID == '2' }}
51        run: echo testing 2

Sample Workflow Run#

../../_images/conditional-job-and-step.png

Reference#