Connect Spanner with a GKE cluster

This page describes how to grant your Google Kubernetes Engine (GKE) cluster permissions to access your Spanner database.

GKE is a managed Kubernetes service that makes it easy to deploy and manage containerized applications. By using GKE and Spanner together, you can take advantage of scalability, reliability, security, and high availability in your application layer and in your database layer.

Your GKE cluster can access the Spanner API through Workload Identity. Workload Identity allows a Kubernetes service account in your cluster to act as an IAM service account. The IAM service account provides Application Default Credentials for your pods, so that you don't need to configure each pod to use your personal user credential.

After you configure your applications to authenticate using Workload Identity, you can use Spanner client libraries to query your Spanner databases. You can also migrate your applications to your GKE node pools.

To create a connection in a sample environment, try the Connecting Spanner with GKE Autopilot codelab.

Enable Workload Identity

If you haven't done so already, enable Workload Identity for your GKE cluster. You can enable Workload Identity on a new cluster by creating a new node pool or you can enable Workload Identity on an existing node pool. GKE autopilot clusters have Workload Identity enabled by default. For more information, see Enable Workload Identity.

Authenticate connection to Spanner with Workload Identity

Configure your applications to authenticate to Google Cloud by using Workload Identity.

  1. Ensure that your GKE Pod uses a Kubernetes ServiceAccount object, as described in Configure authorization and principals.

  2. Create an IAM allow policy that grants the necessary Spanner IAM roles to the Kubernetes ServiceAccount object. The following example grants the Spanner Database User (roles/spanner.databaseUser) role:

      gcloud projects add-iam-policy-binding PROJECT_ID \
          --member="principal:// \
          --role=roles/spanner.databaseUser \

    Replace the following:

    • PROJECT_ID: The project ID of the GKE cluster.
    • PROJECT_NUMBER: The numerical Google Cloud project number.
    • NAMESPACE: The Kubernetes namespace that contains the ServiceAccount.
    • KSA_NAME: The name of the ServiceAccount.

Connect Spanner databases

After your application Pod is authenticated, you can use one of the Spanner client libraries to query your Spanner database.

What's next