bash - 如何获取失败的 BashOperator 的退出代码?
问题描述
我可以根据这个有用的教程为失败的进程集成 Slack 通知。
def task_fail_slack_alert(context):
"""
Sends message to a slack channel.
If you want to send it to a "user" -> use "@user",
if "public channel" -> use "#channel",
if "private channel" -> use "channel"
"""
slack_channel = BaseHook.get_connection(SLACK_CONN_ID).login
slack_token = BaseHook.get_connection(SLACK_CONN_ID).password
failed_alert = SlackAPIPostOperator(
task_id='slack_failed',
channel=slack_channel,
token=slack_token,
text="""
:red_circle: Task Failed.
*Task*: {task}
*Dag*: {dag}
*Execution Time*: {exec_date}
*Log Url*: {log_url}
""".format(
task=context.get('task_instance').task_id,
dag=context.get('task_instance').dag_id,
ti=context.get('task_instance'),
exec_date=context.get('execution_date'),
log_url=context.get('task_instance').log_url,
)
)
return failed_alert.execute(context=context)
task_with_failed_slack_alerts = BashOperator(
task_id='fail_task',
bash_command='exit 1',
on_failure_callback=slack_failed_task,
provide_context=True,
dag=dag)
context
从上面的代码示例中,我可以看到我们可以使用传递给函数的变量来获取有关任务的信息task_fail_slack_alert(context)
,例如task=context.get('task_instance').task_id
我想知道我们是否可以通过包含失败的实际原因来使这个松弛通知更具信息性。如果我们的 bash 脚本以特定的退出代码退出,这是传递给context
发送给on_failure_callback
函数的字典吗?
例如:
if context.get('task_instance').error_code == 2:
message_error = 'Duplicate Key Violation'
else:
message_error = 'Unknown error, investigate logs'
failed_alert = SlackAPIPostOperator(
task_id='slack_failed',
channel=slack_channel,
token=slack_token,
text="""
:red_circle: Task Failed.
*Task*: {task}
*Dag*: {dag}
*Execution Time*: {exec_date}
*Log Url*: {log_url}
*Error*: {message_error}
""".format(
task=context.get('task_instance').task_id,
dag=context.get('task_instance').dag_id,
ti=context.get('task_instance'),
exec_date=context.get('execution_date'),
log_url=context.get('task_instance').log_url,
message_error=message_error,
)
)
return failed_alert.execute(context=context)
解决方案
推荐阅读
- javascript - 动态更新内容(例如单击按钮更新 div)并更新网站上的 url 而无需刷新,然后在手动刷新时保持在同一页面上
- angular - 清晰度组件上的内容投影
- python-3.x - 使用 zipapp 安装以前发布的 virtualenv
- javascript - 显示带有来自strapi的反应的图像
- gradle - Gradle 中是否共享子依赖项?
- python - 是否可以每次在 tkinter 中调用一个函数?
- apache - 如何将 Apache 配置为启用 ADFS SAML 的站点的反向代理
- c - 如何在 C 语言中的单个 scanf/gets 中获得全名?
- javascript - Leetcode 似乎没有接受我对 Rotate Array 的回答
- vue.js - vuetify 选择占位符颜色