如何在Airflow中运行bash脚本文件

Dou*_*ger 15 python airflow

我有一个bash脚本,它创建一个我想在Airflow中运行的文件(如果它不存在),但是当我尝试它失败时.我该怎么做呢?

#!/bin/bash
#create_file.sh

file=filename.txt

if [ ! -e "$file" ] ; then
    touch "$file"
fi

if [ ! -w "$file" ] ; then
    echo cannot write to $file
    exit 1
fi
Run Code Online (Sandbox Code Playgroud)

这就是我在Airflow中调用它的方式:

create_command = """
 ./scripts/create_file.sh
"""
t1 = BashOperator(
        task_id= 'create_file',
        bash_command=create_command,
        dag=dag
)

lib/python2.7/site-packages/airflow/operators/bash_operator.py", line 83, in execute
    raise AirflowException("Bash command failed")
airflow.exceptions.AirflowException: Bash command failed
Run Code Online (Sandbox Code Playgroud)

Jea*_*bre 17

从教程中可以这样:

t2 = BashOperator(
    task_id='sleep',
    bash_command='sleep 5',
    retries=3,
    dag=dag)
Run Code Online (Sandbox Code Playgroud)

但是你要传递一个多行命令

create_command = """
 ./scripts/create_file.sh
"""
Run Code Online (Sandbox Code Playgroud)

应该

create_command = "./scripts/create_file.sh "
Run Code Online (Sandbox Code Playgroud)

此外,您还必须确保您位于正确的目录中以避免出现神秘错误.这样做是这样的:

create_command = "./scripts/create_file.sh"
if os.path.exists(create_command):
   t1 = BashOperator(
        task_id= 'create_file',
        bash_command=create_command,
        dag=dag
   )
else:
    raise Exception("Cannot locate {}".format(create_command))
Run Code Online (Sandbox Code Playgroud)

  • 有时你可能会收到错误:`这个找不到Jinja模板失败了',为了克服脚本末尾添加`space`,不确定是什么驱动这种行为:ref:https://cwiki.apache.org/汇合/显示/ AIRFLOW /常用+陷阱 (9认同)
  • 在.sh之后添加空格:"./ scripts/create_file.sh" (7认同)
  • @KarolSudol这是因为气流会检查您传入的行的末尾,如果它以.sh结尾,它会尝试将其视为模板.一个空格中断检查,它不会将其视为模板.不过,我仍然无法弄清楚原因. (5认同)