Auto-cancel workflow via run step

Cancel Specific Workflow if Newer Commit Exists

At the moment the "Auto-cancel redundant builds" feature is an all or nothing situation, and doesn't allow granular control to allow specific workflows to always run.

We do have an open feature request for this functionality, and if you are wanting this built into the product I recommend adding your comments and vote to the request.

In the meantime though, you could use a run step to accomplish this. To utilize the run step below you will need to generate a personal API token and then store that token as an environment variable, in this case called CIRCLE_API_TOKEN.

- run:
    name: Check for newer workflow
    background: true
    command: |
      while true; do
        sleep 5
        LATEST_COMMIT=$(git ls-remote $CIRCLE_REPOSITORY_URL | grep $CIRCLE_BRANCH | cut -f 1)
        if [ "$LATEST_COMMIT" != "$CIRCLE_SHA1" ]; then
          echo "more recent commit to branch, exiting"
          curl -X POST "https://circleci.com/api/v2/workflow/$CIRCLE_WORKFLOW_ID/cancel?circle-token=$CIRCLE_API_TOKEN"
        fi
      done

The above step would need to be added as one of the first run steps in every job in the workflow that you want to cancel. You will leave it out of the workflows you want to always run. In addition, you would disable the "Auto-cancel redundant builds" feature in your Advanced Project Settings.

What the above step does is check to see if a newer commit exists for the branch you are building on, and if it finds such a case, will send a cancel API request to the currently running workflow.

 

Additional Resources

Was this article helpful?
10 out of 17 found this helpful

Comments

0 comments

Article is closed for comments.