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

26

我有一个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

这是我在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
2个回答

25

从这个教程来看,这是可以的:

t2 = BashOperator(
    task_id='sleep',
    bash_command='sleep 5',
    retries=3,
    dag=dag)

但是你正在将多行命令传递给它

create_command = """
 ./scripts/create_file.sh
"""

应该是这样的

create_command = "./scripts/create_file.sh "

另外,您还必须确保您在正确的目录中,以避免出现难以理解的错误。例如,可以像这样操作:

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))

10
在 ".sh" 后面添加空格: "./scripts/create_file.sh "。 - elcomendante
16
有时你可能会遇到错误:“This fails with Jinja template not found”,为了克服这个问题,在脚本末尾添加一个“空格”,不确定是什么导致了这种行为。参考:https://cwiki.apache.org/confluence/display/AIRFLOW/Common+Pitfalls - elcomendante
9
@KarolSudol之所以这样做,是因为Airflow会检查您输入的行末是否以.sh结尾,如果是,则尝试将其视为模板。 空格会打破这种检查,它就不会将其视为模板。虽然我仍然无法弄清楚其中的原因。 - Gregory Arenius
谢谢你的空间提示 - 我自己肯定想不到。 - andrewm4894
Jinja语法定义要求在定义的运算符的开头和结尾添加空格,例如{{ operator }},其余部分看起来不错。 - Piyush Ugale
template_ext = ('.sh', '.bash',) 这些扩展名在 Operator 类中被定义为模板扩展名。因此,它们被视为模板而不是文件执行。 - Nabin

2

文档中得知:

t2 = BashOperator(
    task_id='bash_example',
    # "scripts" folder is under "/usr/local/airflow/dags"
    bash_command="scripts/test.sh",
    dag=dag)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接