Aron T
07/24/2024, 8:07 PMMarvin
07/24/2024, 8:07 PMfrom prefect import flow
from prefect.blocks.core import Block
from prefect.settings import PREFECT_API_URL
def notify_slack(flow, flow_run, state):
slack_webhook_block = Block.load("slack-webhook/my-slack-webhook")
slack_webhook_block.notify(
(
f"Your job {flow_run.name} entered {state.name} "
f"with message:\n\n"
f"See <https://{PREFECT_API_URL.value()}/flow-runs/"
f"flow-run/{flow_run.id}|the flow run in the UI>\n\n"
f"Tags: {flow_run.tags}\n\n"
f"Scheduled start: {flow_run.expected_start_time}"
)
)
3. Use the Notification Hook in a Flow:
- Configure the flow to use the on_failure
hook to call the notify_slack
function.
@flow(on_failure=[notify_slack], retries=1)
def failing_flow():
raise ValueError("oops!")
if __name__ == "__main__":
failing_flow()
This example configures a flow to send a Slack notification if the flow enters a failed state.
References:
- State Change Hooks Documentation: https://docs.prefect.io/latest/guides/state-change-hooks/
- Slack Integration Documentation: https://docs.prefect.io/latest/integrations/prefect-slack/
For more detailed information, refer to the provided links.Aron T
07/24/2024, 8:25 PMMarvin
07/24/2024, 8:25 PMSlackCredentials
for OAuth tokens and SlackWebhook
for Webhook URLs.
3. Store Credentials in Prefect Cloud:
- You can store these credentials using the Prefect UI.
Step-by-Step Instructions:
- For Slack Webhook:
1. Go to the Prefect Cloud UI.
2. Navigate to Blocks.
3. Create a new block and select SlackWebhook.
4. Set the block name and input the Webhook URL.
- For Slack OAuth Token:
1. Go to the Prefect Cloud UI.
2. Navigate to Blocks.
3. Create a new block and select SlackCredentials.
4. Set the block name and input the Bot User OAuth token.
Example Code:
To load and use these credentials in your flow, you can use the following example:
from prefect import flow
from prefect.blocks.core import Block
from prefect.settings import PREFECT_API_URL
def notify_slack(flow, flow_run, state):
slack_webhook_block = Block.load("slack-webhook/my-slack-webhook")
slack_webhook_block.notify(
(
f"Your job {flow_run.name} entered {state.name} "
f"with message:\n\n"
f"See <https://{PREFECT_API_URL.value()}/flow-runs/"
f"flow-run/{flow_run.id}|the flow run in the UI>\n\n"
f"Tags: {flow_run.tags}\n\n"
f"Scheduled start: {flow_run.expected_start_time}"
)
)
@flow(on_failure=[notify_slack], retries=1)
def failing_flow():
raise ValueError("oops!")
if __name__ == "__main__":
failing_flow()
References:
- Prefect Slack Integration: https://docs.prefect.io/latest/integrations/prefect-slack/
- Slack Credentials Documentation: https://docs.prefect.io/latest/integrations/prefect-slack/credentials/
These steps should help you set up Slack notifications for your job failures.