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 as a user or service account with IAM database authentication

You log in as a database user with IAM database authentication using your email address as the username and an OAuth 2.0 access token with the Cloud SQL Admin API scope as the password.

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

  1. Authenticate to IAM using gcloud auth login.

    gcloud auth login
    
  2. Log in with the psql client using the saved access token.

    Warning: You can use your OAuth 2.0 token to make authenticated requests on your behalf. Make sure to keep it secure, and be careful where you store it or who has access to your instance.

    Replace the following:

    • HOSTNAME: The IP address of the instance, or 127.0.0.1 if using the Cloud SQL proxy.
    • EMAIL: The user email address to use to connect to the host machine.
    • DATABASE_NAME: The name of the database to connect to.
    PGPASSWORD=$(gcloud auth print-access-token) psql --host=HOSTNAME \
                                                      --username=EMAIL \
                                                      --dbname=DATABASE_NAME
    

What's next