Cancel pipeline from job or how to flush output buffer

Not for the first time I am looking for ways to cancel a pipeline from within a job.

True, I can have a job with a script that returns a non-zero exit code like so.

my-job:
  script:
    - |
      echo something
      if whatever; then
        echo else
        exit 42
      fi

This will fail the job and thus also the pipeline. It’ll be marked as failed rather than cancelled.

So, I tried to be clever and cancel the pipeline through the API like so:

my-job:
  script:
    - |
      echo something
      if whatever; then
        echo else
        curl --request POST --header "PRIVATE-TOKEN: $MY_TOKEN" "$CI_API_V4_URL/projects/$CI_PROJECT_ID/pipelines/$CI_PIPELINE_ID/cancel"
      fi

This works just fine but…the pipeline gets cancelled so quickly that not even the output buffer is flushed. Hence, I loose all echo ... output.

So, is there a better way to cancel the pipeline on dynamic conditions? If not, how could I ensure the stdout buffer is flushed before I cancel it?

Hey, there! I found your approach of using API cancellation very clever. After running some tests, I was able to verify that if you use a sleep command before the cancellation command, your output might be printed.

1 Like

Thanks Karla, what is the sleep duration you tested with?

P.S. I had also cross-posted this to SO at Cancel GitLab pipeline from job OR how to flush output buffer - Stack Overflow

Hello. I used 10 seconds, but to be honest I didn’t try out with multiple values. Perhaps it doesn’t need all that much… But for testing purposes, I tried 10 and it worked well.

I tried 10 and 20 seconds, but still not able to show the logs.
I ended up using the 2 jobs solution (mentioned also in Stackoverflow), one to review if I need to cancel the job, and another just to cancel it.