Skip to content
Advertisement

Add GCP credentials to airflow via command line

Airflow allows us to add connection information via command-line airflow connections. This can help with automated deployment of airflow installations via ansible or other dev-ops tools.

It is unclear how connections to google cloud platform (service accounts) can be added to ariflow via command line.

Advertisement

Answer

Pre airflow 1.9 the following example outlines how to use a DAG to add connection information: 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()

From airflow 1.9 forward one can:

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"}'
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement