Conditionally skip the remaining pipeline jobs

Everyone can contribute. Help move this issue forward while earning points, leveling up and collecting rewards.

I have a pipeline with the following stages.

Install -> Lint -> Test -> Build

In the script definition of the Install stage, i hv a conditional checking. ex:

Install:
  stage: Install
  script:
    >
      if ( sth == true ); then
        echo -e "Move on to the next job";
      else
        echo -e "Cancel the remaining jobs";
      fi;

Right now it only prints the statement without really cancelling all the jobs. Is it possible that i could cancel/skip the remaining jobs base on the above conditional statement? In that case i could reduce the time of the pipeline?

Proposed workaround

Other solution(that works even right now) is to use the API for canceling a job. The only downside of this is that it requires a private access token:

test1:
  image: alpine
  script:
    - echo "This job will cancel the pipeline"
    - apk add --update curl
    - 'curl --request POST --header "PRIVATE-TOKEN: ${MY_PAT_TOKEN}" "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/jobs/${CI_JOB_ID}/cancel"'

I think we should allow the usage of CI_JOB_TOKEN for authentication for this endpoint. Note: we should only allow a job to cancel itself, not other jobs: Job.find_by_token("$CI_JOB_TOKEN").id == "$CI_JOB_ID".

Example project that uses PAT to cancel pipelines: https://gitlab.com/mbobin/ci-playground/-/blob/81e71dbd716bc8428777cc4a33495667041888c5/.gitlab-ci.yml and a relevant pipeline for it: https://gitlab.com/mbobin/ci-playground/-/pipelines/229560149

This can be extracted into a Bash function:

test1:
  stage: test
  before_script:
    - apk add --update curl
    - | 
        cancel_pipeline () {
          curl --request POST --header "PRIVATE-TOKEN: ${MY_PAT_TOKEN}" "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/jobs/${CI_JOB_ID}/cancel"
        }
  script:
    - echo "This job will cancel the pipeline"
    - cancel_pipeline

And it can abstracted further by moving it to a template and used with include and extends:

# cancel_pipeline_functions.yml
.cancel_pipeline_template:
  image: alpine:latest
  before_script:
    - apk add --update curl
    - | 
        cancel_pipeline () {
          curl --request POST --header "PRIVATE-TOKEN: ${MY_PAT_TOKEN}" "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/jobs/${CI_JOB_ID}/cancel"
        }

# .gitlab-ci.yml
image: alpine:latest
include: cancel_pipeline_functions.yml

test1:
  stage: test
  extends: .cancel_pipeline_template
  script:
    - echo "This job will cancel the pipeline"
    - cancel_pipeline
Edited by 🤖 GitLab Bot 🤖