Logging in to a database with IAM database authentication

This page describes how users and service accounts can log in to Cloud SQL databases using Cloud SQL IAM database authentication. To learn more about the Cloud SQL IAM integration, see Overview of Cloud SQL IAM database authentication.

Before you begin

Logging in with IAM database authentication

Using the Cloud SDK, you can explicitly request an OAuth 2.0 token with the Cloud SQL for MySQL API scope that you are using to log in to the database through the mysql client. When you log in as a database user with IAM database authentication, you use your email address and the access token as the password.

For this procedure, you must:

To use the Cloud SDK to generate this token and log in:

User

  1. Authenticate to IAM with Application Default Credentials using gcloud auth application-default login while specifying the Cloud SQL for MySQL API scope to authorize.

    For more information, see Authorizing with Application Default Credentials.

  2. Generate an access token and log in with a client.

    Replace the following:

    • HOSTNAME: The IP address of the instance, or 127.0.0.1, if using the Cloud SQL proxy.
    • USERNAME: The user's email address, without the @ or domain name. For example, for test-user@gmail.com, enter test-user.
    MYSQL_PWD=$(gcloud auth application-default print-access-token) mysql \
        --enable-cleartext-plugin \
        --ssl-ca=server-ca.pem \
        --ssl-cert=client-cert.pem \
        --ssl-key=client-key.pem \
        --host=HOSTNAME \
        --user=USERNAME

Service account

  1. Authenticates to IAM using gcloud auth activate-service-account. For service account of a GCE VM instance, use gcloud compute instances set-service-account to specify the Cloud SQL for MySQL API scope to authorize.

    For more information, see Authorizing with a service account.

  2. Generate an access token and log in with a client.

    Replace the following:

    • SERVICE_ACCOUNT: The service account's email.
    • HOSTNAME: The IP address of the instance, or 127.0.0.1, if using the Cloud SQL proxy.
    • USERNAME: The service account's email address without the @project-id.iam.gserviceaccount.com suffix.
    MYSQL_PWD=$(gcloud auth print-access-token SERVICE_ACCOUNT) mysql \
        --enable-cleartext-plugin \
        --ssl-ca=server-ca.pem \
        --ssl-cert=client-cert.pem \
        --ssl-key=client-key.pem \
        --host=HOSTNAME \
        --user=USERNAME

What's next