您可以在 DAG 中添加一个步骤,如果环境中尚不存在连接,它将以编程方式添加连接:
def add_connection_callable(**kwargs):
connection: Connection = Connection(
conn_id="foo",
conn_type="HTTP",
host=kwargs['host'],
port=kwargs['port']
)
session: Session = settings.Session
db_connection: Connection = session.query(Connection) \
.filter(Connection.conn_id == "foo") \
.first()
if db_connection is None:
logging.info("Adding connection \"foo\"..")
session.add(connection)
session.commit()
else:
logging.info("Connection \"foo\" already exists.")
add_connection: PythonOperator = PythonOperator(
task_id="add_connection",
python_callable=add_connection_callable,
op_kwargs={
"host": "{{ dag_run.conf['Host'] }}",
"port": "{{ dag_run.conf['Port'] }}"
},
dag=dag)