手动运行Airflow DAG时,如何从UI配置中获取Bash Operator的参数?
Airflow中Bash Operator获取手动运行传入配置参数的方法
是的,Bash Operator可以通过Jinja模板语法获取手动运行DAG时传入的配置参数,效果类似Python Operator中通过kwargs和上下文获取参数的方式,具体实现如下:
步骤1:手动运行时传入配置参数
在Airflow UI点击DAG的"Run"按钮后,在弹出窗口的"Configuration JSON"输入框中,传入JSON格式的参数,例如:
{"my_param": "hello_airflow", "count": 5}
步骤2:在Bash Operator中引用参数
Bash Operator的bash_command支持Jinja模板渲染,你可以通过dag_run.conf对象获取传入的配置:
- 使用
{{ dag_run.conf.get('参数名', '默认值') }}语法获取单个参数,默认值用于处理自动调度时无配置的场景。
完整代码示例
from airflow import DAG from airflow.operators.bash import BashOperator from datetime import datetime default_args = { 'start_date': datetime(2024, 1, 1), 'retries': 1 } with DAG( 'bash_get_manual_params', default_args=default_args, schedule_interval=None, # 手动触发的DAG catchup=False ) as dag: # 打印传入的参数 print_param = BashOperator( task_id='print_param', bash_command=''' echo "手动传入的my_param值: {{ dag_run.conf.get('my_param', '未传入') }}" echo "手动传入的count值: {{ dag_run.conf.get('count', 0) }}" ''' ) # 使用参数执行外部脚本 run_with_param = BashOperator( task_id='run_with_param', bash_command='python /path/to/your/script.py --param {{ dag_run.conf.get('my_param', 'default') }}' ) print_param >> run_with_param
注意事项
- 若DAG存在自动调度场景,必须设置默认值,否则自动运行时
dag_run.conf不存在会导致渲染报错。 - 对于字典、列表等复杂类型参数,需要通过Jinja的
tojson过滤器转成bash可识别的格式,避免语法错误。 - Airflow 2.x版本中,Bash Operator默认开启模板渲染,无需额外配置
provide_context=True。
内容的提问来源于stack exchange,提问作者vashi
相关产品推荐
相关产品推荐

