Getting job failure message to send via Slack Orb (4.3.1)

We’re starting to use the Slack orb and are currently using the supplied templates. However, we’d like to see the failure reason in the Slack message for convenience.

I would imagine that getting the failure reason when it’s due to compilation failure would require scripting on my part and then storing the message in an environment variable to access in the slack/notify step. However, when it’s a CircleCI failure like Too long with no output: Context deadline exceeded, is there a way to access that within the config?

Has anyone else successfully sent failure reasons via the Slack orb?

Hi!

I believe this would be possible by utilizing our API.

The information for a job can be obtained in the following way:

First you will need to get the build information for the step that failed.
You could get that information by running a query like this:

curl https://circleci.com/api/v1.1/project/github/{orgname}/{project name}/ -H "Circle-Token: <circle-token>"

Then you can filter the results for steps where failed is true, and get the url in build_url.

Following that, you can run the following query using the url from above:

curl https://circleci.com/api/v1.1/project/github/{orgname}/{project name}/{job number} -H "Circle-Token: <circle-token>"

This will give you a json response, which contains a URL to the output log of each step under the key output_url.

You could then curl that log, and parse out the information you need for your error message.
After that, you could pass in the message into a variable. Since CircleCI uses a different shell environment for each step, you will need a step like this in your config:

echo "export SLACK_ERROR_MESSAGE='${SLACK_MESSAGE}'" >> $BASH_ENV
where SLACK_MESSAGE is where you stored the output from the log, and SLACK_ERROR_MESSAGE is the variable you will use to insert the message into your slack orb template.

It is probably possible to make this more dynamic (such as utilizing the CIRCLE_BUILD_URL and other environment variables made available in all builds) so that you don’t have to hardcode in the org/project names.

Let us know if this helps point you in the right direction.

1 Like

I took a look at some of our other posts, and noticed that we have a Support Solution post regarding this topic. I think it explains in more detail the process I was describing, so please took a look:

1 Like