How to trigger codefresh hooks based on condition

519 Views Asked by At

I am trying to ensure that if our build fails we get notified by slack BUT only for our main branch.

Here is our code for the slack notification:

hooks:
  on_fail:
    steps:
      notify:
        image: codefresh/slacknotifier
        environment:
          - SLACK_HOOK_URL=<webhook url>
          - SLACK_ATTACHMENTS=<slack message>
      when:
        branch:
          only:
            - /^(main)/i

At the minute it is still slacking for feature branches. Any assistance would be greatly appreciated.

2

There are 2 best solutions below

0
On

Stephen, I'm wondering if it was a bug that has been fixed as I ran pretty much the same code(same condition at least)

version: "1.0"

hooks:
  on_fail:
    steps:
      notify:
        type: slack-notifier
        arguments:
          MODE: text
          SLACK_TEXT: "stackoverflow test"
          SLACK_HOOK_URL: ${{SLACK_HOOK_URL}}
        when:
          branch:
            only:
              - /^(main)/i

and it worked as expected for me

When I'm not on main, I can see in the log:

================ Executing Post Hooks =================
[2022-02-28T22:48:33.892Z] Checking if branch is in only whitelist...
[2022-02-28T22:48:33.893Z] Result for regular expression /^(main)/i: no match
[2022-02-28T22:48:33.894Z] Skipping execution.

Maybe the notification was coming from the user notification setting (https://g.codefresh.io/user/settings) or the Slack integration setting (https://g.codefresh.io/account-admin/account-conf/integration/slack)

0
On

You can treat the actual the codefresh hooks steps the same way as normal steps, so you can try to invoke or set a conditional on the pipeline or with the branch set another step that read the branch properties.

generic

 on_fail:
   steps:
      notify:
        image: codefresh/slacknotifier
        environment:
          - SLACK_HOOK_URL=<webhook url>
          - SLACK_ATTACHMENTS=<slack message>
    when:
      condition:
        any:
          myCondition3: workflow.result == 'approval'

branch based:

 on_fail:
   steps:
      notify:
        image: codefresh/slacknotifier
        environment:
          - SLACK_HOOK_URL=<webhook url>
          - SLACK_ATTACHMENTS=<slack message>
    when:
      branch:
       only:
         - /^FEATURE-.*/i

this last one should apply for all FEATURE-* regex, good luck lml

reference : https://codefresh.io/docs/docs/ci-cd-guides/pull-request-branches/