Search code examples
pythonairflowjinja2

How to get the URL from the DAG in Airflow using templating?


I was trying to send to Slack an alert when the previous task fails but I would like to add the url from the DAG in the text to go easily from slack.

I tried this, but I'm getting an error:

    send_slack_alert = SlackWebhookOperator(
        task_id='slack_alert',
        slack_webhook_conn_id="slack_connection",
        message="There is an error\n"
                "DAG name: {{ dag }}\n"
                "Run: {{ run_id }}\n"
                "url: {{ conf.base_url }}/dags/{{ dag.dag_id }}/grid```",
        trigger_rule=TriggerRule.ONE_FAILED
    )

Error:

'airflow.configuration.AirflowConfigParser object' has no attribute 'base_url'

I was looking this doc from airflow https://airflow.apache.org/docs/apache-airflow/stable/templates-ref.html

Thanks in advance


Solution

  • The AirflowConfigParser has a get() method you can use to retrieve Airflow configuration settings. This method can still be used in a Jinja expression.

    SlackWebhookOperator(
            task_id='slack_alert',
            slack_webhook_conn_id="slack_connection",
            message="There is an error\n"
                    "DAG name: {{ dag.dag_id }}\n"
                    "Run: {{ run_id }}\n"
                    "url: {{ conf.get('webserver', 'BASE_URL') }}/dags/{{ dag.dag_id }}/grid",
            trigger_rule=TriggerRule.ONE_FAILED
        )
    

    Rendered Template enter image description here