Something went wrong…
Slack Notifications with Prefect
Last summer I wrote a flow that monitored the forecast for my apartment and turned on my AC when things got too hot. I now have the flow deployed to Prefect Cloud and run by a local agent on my raspberry pi. All is well but my husband pointed out to me that he rarely checks the Prefect Cloud web app, so he would not know if anything had gone wrong with my flow. He wondered if we could add a notification “to Slack or something” so that he would know if the code had failed.
We’ll be releasing Prefect Cloud integrations for Slack soon (so you can set up Slack notifications even if you don’t add them in your Prefect Core code) but this post talks through the pretty simple process of adding Slack notifications to a Prefect Core flow before deploying it to Cloud.
My Flow
The code for my flow, slightly updated to run using Prefect’s new Dockerless universal deploy feature and a local agent, is:
To actually run this flow, I would need to start my local agent:
prefect agent start local -t TOKEN
TOKEN is a RUNNER-scoped token created from the Team Settings page of the Prefect Cloud UI. You can also create tokens from the Prefect CLI.
To test my Flow off-schedule, I’ll need to create a new flow run for the agent to run:
prefect run cloud -n "TempNov" -p "Temp"
Setting Up Slack
To add slack notifications to my flow, I had to first install the Prefect Application into Slack. There are very clear instructions in the docs so I’ll skip that part but will remind you that it’s not a good idea to send notifications to the #general channel, better to create a channel like “Prefect_Notifications”:
Adding Instructions for Slack into My Flow
After getting into trouble for spamming the #general channel while setting up my flow, I decided I didn’t need to be notified every time my flow ran. Instead, I only want to know about flows that fail. The Slack notifier is customizable and can be set at the top of your code so I set mine up to only notify me about failed tasks like so:
I then set my notifier on my modify task, as that’s the one whose outcome I really care about:
Now if my flow runs into problems and my AC is not going to be set, I get a nice handy message to my Slack account warning me that I need to check my code or passwords and (if it’s hot out there!) actually turn the AC on myself.
There are many other types of notification hooks one could imagine— if we don’t already offer one that you would find useful, please let us know by opening a GitHub issue!