Send Slack alerts on build failures (#189)

* Send Slack alerts on build failures

* Only send Slack notifications for failed cron builds
This commit is contained in:
Nikolay Edigaryev 2024-10-01 22:54:02 +04:00 committed by GitHub
parent 1e710b24b9
commit 74aca70ef6
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 24 additions and 0 deletions

View File

@ -1,3 +1,4 @@
load("cirrus", "env", "http")
load("github.com/cirrus-modules/graphql", "rerun_task_if_issue_in_logs")
def on_task_failed(ctx):
@ -5,3 +6,26 @@ def on_task_failed(ctx):
print("Task is already an automatic re-run! Won't even try to re-run it...")
return
rerun_task_if_issue_in_logs(ctx.payload.data.task.id, "The network connection was lost")
def on_build_failed(ctx):
# Only send Slack notifications for failed cron builds[1]
#
# [1]: https://cirrus-ci.org/guide/writing-tasks/#cron-builds
if "Cron" not in ctx.payload.data.build.changeMessageTitle:
return
resp = http.post("https://slack.com/api/chat.postMessage", headers={
"Content-Type": "application/json",
"Authorization": "Bearer " + env.get("SLACK_TOKEN"),
}, json_body={
"channel": "#image-updates",
"text": "Build <https://cirrus-ci.com/build/{build_id}|{build_id} (\"{change_message_title}\")> failed on branch \"{branch_name}\" in repository \"{repository_name}\".".format(build_id=ctx.payload.data.build.id, change_message_title=ctx.payload.data.build.changeMessageTitle, branch_name=ctx.payload.data.build.branch, repository_name=ctx.payload.data.repository.name),
})
if resp.status_code != 200:
fail("failed to post message to Slack: got unexpected HTTP {}".format(resp.status_code))
resp_json = resp.json()
if resp_json["ok"] != True:
fail("got error when posting message to Slack: {}".format(resp_json["error"]))