Trigger a github workflow before running another workflow on : release [created]

1.7k Views Asked by At

When I create a new release on Github via its UI, I want to trigger the release.yml workflow.

Within the release.yml workflow, I'd like to first run the ci.yml workflow and only if it passes, go ahead and create a release. If the ci.yml worflow fails, remove the newly created release on the Github UI as well.

I have 2 YAML files ci.yml and release.yml

In my release.yml file

on:  
  release:
    types: [created]

jobs:
  # I want to run the ci.yml workflow here and then run the jobs below if it passes.
  # If the ci.yml workflow fails, revert back and remove the created release.


  job1:
    .........


  job2:
    .........

If there is a better way to do achieve this, please let me know.

1

There are 1 best solutions below

0
On

You can make use of workflow_run event with a condition.

For example, in release.yaml, you can add something like this to run a step only if ci workflow has successfully completed:

on:
  workflow_run:
    workflows: [ci]
    types: [completed]

jobs:
  on-success:
    runs-on: ubuntu-latest
    if: ${{ github.event.workflow_run.conclusion == 'success' }}
    steps:
      - run: echo 'This is where your release steps can continue'
  on-failure:
    runs-on: ubuntu-latest
    if: ${{ github.event.workflow_run.conclusion == 'failure' }}
    steps:
      - run: echo 'you can remove this or do something with it like sending an email about why you are not releasing'

There are few other ways to trigger a workflow from another workflow. Some are here:

  1. Using Workflow Dispatch

  2. Repository Dispatch

In your case, if you prefer to use Workflow Dispatch, you can simply invoke the release workflow as last step of ci workflow which will satisfy your needs of running release workflow only when ci is successful.

If you prefer Repository Dispatch, you can dispatch the event at the last step of ci workflow. In this approach you can pass additional inputs to release workflow so that you can have additional flexibility in release workflow.

There are many other way to trigger a workflow which are well documented here. Few of the ways you can consider are: creating a tag in your ci workflow and then use that event in release workflow.