简体   繁体   English

Airflow 通过 bash 操作员执行 python 脚本

[英]Airflow execute python script through bash operator

I have a python script test2.py to connect to a remote server and execute the command.我有一个 python 脚本 test2.py 来连接到远程服务器并执行命令。 as below.如下。 This works on the command line.这适用于命令行。

Passing parameters as JSON and getting the response in JSON this works when executed as below in the command line.将参数作为 JSON 传递并在 JSON 中获取响应,这在命令行中执行如下时有效。

python3.6 test2.py  '{"hostname": "<server>", "username":"<test>", "password":"<test1>", "command1":"hostname"}'

I am trying to execute same through the airflow我正在尝试通过 airflow 执行相同的操作

from __future__ import print_function
from airflow.operators import BashOperator
from airflow.models import DAG
from datetime import datetime, timedelta


default_args = {
    'owner': 'airflow',
    'depends_on_past': False,
    'start_date': datetime(2018, 9, 1),
    'email_on_failure': False,
    'email_on_retry': False,
    'schedule_interval': '@daily',
    'retries': 1,
    'retry_delay': timedelta(seconds=5),
}

dag = DAG(
    dag_id='DAG-3',
    default_args=default_args,
    dagrun_timeout=timedelta(minutes=10)
    )

cmd_command = "python3.6 /root/test2.py '{{"hostname": "<server>", "username":"<test>", "password":"<test1>", "command1":"hostname"}}'"


t = BashOperator(
     task_id = 'some_id',
     bash_command = cmd_command,
     dag = dag)
 

I am seeing below error related to syntax.?我看到以下与语法相关的错误。?

cmd_command = "python3.6 /root/test2.py '{{"hostname": "<server>", "username":"<test>", "password":"<test1>", "command1":"hostname"}}'"
                                                       ^
SyntaxError: invalid syntax

Can you please help你能帮忙吗

Thank you谢谢

You use double quotes for JSON, but Python interprets them as start or end of a string.您对 JSON 使用双引号,但 Python 将它们解释为字符串的开头或结尾。 One way to resolve this is to escape double quotes inside JSON:解决这个问题的一种方法是在 JSON 中转义双引号:

cmd_command = "python3.6 /root/test2.py '{\"hostname\": \"<server>\", \"username\":\"<test>\", \"password\":\"<test1>\", \"command1\":\"hostname\"}'"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM