Friday, 7 August 2020

How to Run GitHub Actions Step When a Failure Occurred in a Previous Step

GitHub Actions are the CI/CD workflow implementation tool built into GitHub repos. While using the GitHub Actions workflows you may want to execute a cleanup, or rollback or even a ticket(issue) creation task in a situation where a job step is failed. In Azure DevOps pipelines each task had control support to easy implantations of the run on failure need. Let’s look at what it is in Azure DevOps then understand how we can achieve same goals in GitHub actions workflow steps.

In Azure DevOps pipelines you could easily achieve this type of a need in tasks by using control options.


In case of Azure DevOps YAML pipelines, the same set of control could be implemented the information from Microsoft docs (https://docs.microsoft.com/en-us/azure/devops/pipelines/process/tasks?view=azure-devops&tabs=yaml#conditions) is below.


In GitHub actions to execute a step in a job only when one of the previous step is failed you can use if: ${{ failure() }} in the step which needs to run on failure of previous step. For example, in below workflow we are purposefully failing a step by using exit code 1, and on the failure an issue in the repo is created using another step set to run at failures.

on: [push]
 
jobs:
  FailJobIssueDemo:
    runs-on: ubuntu-latest
    steps:
      - name: Step is going to pass
        run: echo Passing step
      
      - name: Step is going to fail
        run: exit 1
         
      - name: Step To run on failure
        if: ${{ failure() }}
        run: |
          curl --request POST \
          --url https://api.github.com/repos/${{ github.repository }}/issues \
          --header 'authorization: Bearer ${{ secrets.GITHUB_TOKEN }}' \
          --header 'content-type: application/json' \
          --data '{
            "title": "Issue created due to workflow fialure: ${{ github.run_id }}",
            "body": "This issue was automatically created by the GitHub Action workflow **${{ github.workflow }}**. \n\n due to failure in run: _${{ github.run_id }}_."
            }'

The step created issue in the repository can be seen after workflow execution as below.

No comments:

Popular Posts