Trying to rescue a condition when previous steps are not run due to the if statement

I want to notify to slack if the first step of the workflow succeeded, or failed.

I have the following workflow, which checks if the 1st step succeeds, and if it does,

it messages via slack with “success”. And if not, it messages via slack with “Something went wrong!”

on:  
 push:  
 branches:  
 - master  
  
jobs:
my-job:
name: Something something
runs-on: ubuntu-latest
env:
SLACK\_OVERRIDE\_MESSAGE: true
SLACK\_WEBHOOK: ${{ secrets.SLACK_WEBHOOK_URL }}
steps:
-name: **This will never run because the ref is always master**
if: github.ref == 'refs/heads/develop'
run: some script
-name: Notify slack when success
if: success()
uses: Ilshidur/action-slack@master
with:
args:"Success!"  
 - name: Notify slack when its not run  
 if: cancelled() \<= This is where I'm having problem with  
 uses: Ilshidur/action-slack@master  
 with:   
 args: "Something went wrong!"

But to my current knowledge, there is no way to know if the first (or an arbitrary step) has failed in the 3rd step because it can’t backtrack more that 2steps.

So I’m trying to overcome that limitation by chaining the steps using the <if> and <success> and <cancelled> statements.

But when I try this, the 3rd step will never be run, because if the 1st step fails, then the 2nd step’s status would be “NOT RUN(?)” and there is no current way to handle that situation.

I tried using <if: !success()> which resulted with an error, which says

Your workflow file was invalid: The pipeline is not valid. .github/workflows/test.yml: Unexpected tag '!success()'

If there are any ways to condition a workflow with the success or failure within an arbitrary step, I would be very happy.

Or just any work around for this situation is highly appreciated.

Thank you.

The job status check functions ‘success(), failure()…’ only check the previous step status in the job. As a workaround, please set the ‘outputs’ for the 1st step, and check the value with ‘if’ in the behind steps. Code sample as below:

jobs:
  my-job:
    name: Something something
    runs-on: ubuntu-latest
    steps:
      - name: set output
        id: step1
        run: |
          echo ::set-output name=status::failure
        continue-on-error: true

      - name: Notify slack when success
        if: steps.step1.outputs.status == 'success'
        run: |
          echo "Success!"
      - name: Notify slack when it not run
        if: steps.step1.outputs.status != 'success'
        run: |
          echo "Something went wrong!"

stepstatus.png

1 Like

Thank you very much weide-zhou!
This worked for me nicely.

1 Like