通过命令行将GCP凭据添加到Airflow

3
Airflow允许我们通过命令行airflow connections添加连接信息。这可以帮助使用ansible或其他dev-ops工具自动部署airflow安装。
目前还不清楚如何通过命令行将连接到Google Cloud Platform(服务帐户)添加到Ariflow中。
3个回答

9

在Airflow 1.9之前,以下示例说明如何使用DAG添加连接信息:https://gist.github.com/yu-iskw/42f9f0aa6f2ff0a2a375d43881e13b49

def add_gcp_connection(ds, **kwargs):
    """"Add a airflow connection for GCP"""
    new_conn = Connection(
        conn_id=<CONNECTION_ID>,
        conn_type='google_cloud_platform',
    )
    scopes = ['https://www.googleapis.com/auth/cloud-platform']
    conn_extra = {
        "extra__google_cloud_platform__scope": ",".join(scopes),
        "extra__google_cloud_platform__project":
            "<GCP_PROJECT_NAME>",
        "extra__google_cloud_platform__key_path":
            "<GCP_CREDENTIALS_ABSOLUTE_PATH.json>"
    }
    conn_extra_json = json.dumps(conn_extra)
    new_conn.set_extra(conn_extra_json)

    session = settings.Session()
    session.add(new_conn)
    session.commit()

从Airflow 1.9开始,可以:

airflow connections -a \
  --conn_id=<CONNECTION_ID> \
  --conn_type=google_cloud_platform \
  --conn_extra='{ "extra__google_cloud_platform__key_path":" '`
        `'<GCP_CREDENTIALS_ABSOLUTE_PATH.json>", '`
    `'"extra__google_cloud_platform__project": '`
        `'"<GCP_PROJECT_NAME>", '`
    `'"extra__google_cloud_platform__scope":  '`
        `'"https://www.googleapis.com/auth/cloud-platform"}'

0

这是一个在Airflow 2.2.5中可用的更易读的示例。
这里是JSON文件test.json:

{"test2_gcp_connection": {
"conn_type": "google_cloud_platform",
"description": null,
"host": null,
"login": null,
"password": null,
"schema": null,
"port": null,
"extra": "{ \"extra__google_cloud_platform__key_path\": \"/path/to/key.json\", \"extra__google_cloud_platform__project\": \"project_name\", \"extra__google_cloud_platform__scope\": \"https://www.googleapis.com/auth/cloud-platform\"}"}}

你可以使用以下命令:
airflow connections import test.json

您的GCP连接将被创建。

类似地,您可以使用以下命令将已创建的airflow连接导出到名为test.json的文件中:

airflow connections export test.json

另一种以类似但比第一个答案更简化的方式编写它的方法:

airflow connections add 'test_gcp_connection' --conn-type=google_cloud_platform --conn-extra='{ "extra__google_cloud_platform__key_path": "path/to/key.json", "extra__google_cloud_platform__project": "projectname", "extra__google_cloud_platform__scope": "https://www.googleapis.com/auth/cloud-platform"}'

0

自发布此文以来,已添加了有关Google Cloud连接的文档:https://airflow.apache.org/docs/apache-airflow-providers-google/stable/connections/gcp.html

作为使用--conn_extra的替代方案,该方法可以使将值替换为json字符串变得具有挑战性,您可以使用conn_uri。例如:

# AIRFLOW_CONN_GOOGLE_CLOUD_DEFAULT='google-cloud-platform://'
# GCP_PROJECT='<your-gcp-project>'
airflow connections \
  --add \
  --conn_id '<CONNECTION_ID>' \
  --conn_uri "${AIRFLOW_CONN_GOOGLE_CLOUD_DEFAULT}?extra__google_cloud_platform__project=${GCP_PROJECT}"

您可以添加尽可能多的URI参数,用&分隔。


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