I wrote quick Python script that generates a connection-commands.sh
file with ALL the connections in one airflow environemnt, that can be run in a second airflow environemnt to import the connections.
from airflow.models import Connection
from airflow.utils.db import create_session
with create_session() as session:
connections = session.query(Connection).order_by(Connection.conn_id).all()
connection_commands = []
conn: Connection
for conn in connections:
conn_command_lines = [
f"airflow connections",
f"--add",
f"--conn_id='{conn.conn_id}'",
f"--conn_type='{conn.conn_type}'",
]
# add `host`, if non-empty
if conn.host:
conn_command_lines.append(f"--conn_host='{conn.host}'")
# add `port`, if non-empty
if conn.port:
conn_command_lines.append(f"--conn_port='{conn.port}'")
# add `schema`, if non-empty
if conn.schema:
conn_command_lines.append(f"--conn_schema='{conn.schema}'")
# add `login`, if non-empty
if conn.login:
conn_command_lines.append(f"--conn_login='{conn.login}'")
# add `password`, if non-empty
if conn.password:
conn_command_lines.append(f"--conn_password='{conn.password}'")
# add `extra`, if non-empty
if conn.extra:
conn_command_lines.append(f"--conn_extra='{conn.extra}'")
# combine the command lines
conn_command = " \\\n ".join(conn_command_lines) + ";"
connection_commands.append(conn_command)
with open("connection-commands.sh", mode="w") as f:
f.write("#!/usr/bin/env bash")
f.write("\n\n")
for conn_command in connection_commands:
f.write(conn_command)
f.write("\n\n")
Output Format
The format of the generated connection-commands.sh
file is as follows:
#!/usr/bin/env bash
airflow connections \
--add \
--conn_id='my_connection_1' \
--conn_type='http' \
--conn_host='https://example.com' \
--conn_login='user' \
--conn_password='password';
airflow connections \
--add \
--conn_id='my_connection_2' \
--conn_type='http' \
--conn_host='https://example.com' \
--conn_login='user' \
--conn_password='password';
...
WARNING: the airflow connections --add ...
command will only add a connection if the connection does not already exist, you will need to delete the connection first if you want to "update" it.