{"token_count": 4806}

# Database Access with Cloud Spanner

Teleport can provide secure access to Cloud Spanner via the [Teleport Database Service](https://goteleport.com/docs/enroll-resources/database-access.md). This allows for fine-grained access control through [Teleport's RBAC](https://goteleport.com/docs/enroll-resources/database-access/rbac.md).

In this guide, you will:

1. Configure your Cloud Spanner database with a service account.
2. Add the database to your Teleport cluster.
3. Connect to the database via Teleport.

## How it works

The Teleport Database Service uses IAM authentication to communicate with Spanner. When a user connects to the database via Teleport, the Teleport Database Service obtains Google Cloud credentials and authenticates to Google Cloud as an IAM principal with permissions to access the database.

**Self-Hosted**

![Self-Hosted Teleport Architecture for Cloud Spanner Access](https://website.goteleport.com/_uploads/spanner_selfhosted_bf0e74fb75.png)

**Cloud-Hosted**

![Cloud-Hosted Teleport Architecture for Cloud Spanner Access](https://website.goteleport.com/_uploads/spanner_cloud_a781090c6a.png)

## Prerequisites

- A running Teleport cluster. If you want to get started with Teleport, [sign up](https://goteleport.com/signup) for a free trial or [set up a demo environment](https://goteleport.com/docs/get-started/deploy-community.md).

- The `tctl` and `tsh` clients.

  Installing `tctl` and `tsh` clients

  1. Determine the version of your Teleport cluster. The `tctl` and `tsh` clients must be at most one major version behind your Teleport cluster version. Send a GET request to the Proxy Service at `/v1/webapi/find` and use a JSON query tool to obtain your cluster version. Replace teleport.example.com:443 with the web address of your Teleport Proxy Service:

     **Mac/Linux**

     ```
     $ TELEPORT_DOMAIN=teleport.example.com:443
     $ TELEPORT_VERSION="$(curl -s https://$TELEPORT_DOMAIN/v1/webapi/find | jq -r '.server_version')"
     ```

     **Windows - Powershell**

     ```
     $ $TELEPORT_DOMAIN = "teleport.example.com:443"
     $ $TELEPORT_VERSION = (Invoke-RestMethod -Uri "https://${TELEPORT_DOMAIN}/v1/webapi/find").server_version
     ```

  2. Follow the instructions for your platform to install `tctl` and `tsh` clients:

     **Mac**

     Download the signed macOS .pkg installer for Teleport, which includes the `tctl` and `tsh` clients:

     ```
     $ curl -O https://cdn.teleport.dev/teleport-${TELEPORT_VERSION?}.pkg
     ```

     In Finder double-click the `pkg` file to begin installation.

     ---

     DANGER

     Using Homebrew to install Teleport is not supported. The Teleport package in Homebrew is not maintained by Teleport and we can't guarantee its reliability or security.

     ---

     **Windows - Powershell**

     ```
     $ curl.exe -O https://cdn.teleport.dev/teleport-v$TELEPORT_VERSION-windows-amd64-bin.zip
     Unzip the archive and move the `tctl` and `tsh` clients to your %PATH%
     NOTE: Do not place the `tctl` and `tsh` clients in the System32 directory, as this can cause issues when using WinSCP.
     Use %SystemRoot% (C:\Windows) or %USERPROFILE% (C:\Users\<username>) instead.
     ```

     **Linux**

     All of the Teleport binaries in Linux installations include the `tctl` and `tsh` clients. For more options (including RPM/DEB packages and downloads for i386/ARM/ARM64) see our [installation page](https://goteleport.com/docs/installation/single-machine.md).

     ```
     $ curl -O https://cdn.teleport.dev/teleport-v${TELEPORT_VERSION?}-linux-amd64-bin.tar.gz
     $ tar -xzf teleport-v${TELEPORT_VERSION?}-linux-amd64-bin.tar.gz
     $ cd teleport
     $ sudo ./install
     Teleport binaries have been copied to /usr/local/bin
     ```

* A Google Cloud account

* A Cloud Spanner instance and database

* A host to run the Teleport Database Service (for example, a Compute Engine instance) with outbound HTTPS access to `spanner.googleapis.com:443`

* To check that you can connect to your Teleport cluster, sign in with `tsh login`, then verify that you can run `tctl` commands using your current credentials. For example, run the following command, assigning teleport.example.com to the domain name of the Teleport Proxy Service in your cluster and email\@example.com to your Teleport username:

  ```
  $ tsh login --proxy=teleport.example.com --user=email@example.com
  $ tctl status
  Cluster  teleport.example.com
  Version  19.0.0-dev
  CA pin   sha256:abdc1245efgh5678abdc1245efgh5678abdc1245efgh5678abdc1245efgh5678
  ```

  If you can connect to the cluster and run the `tctl status` command, you can use your current credentials to run subsequent `tctl` commands from your workstation. If you host your own Teleport cluster, you can also run `tctl` commands on the computer that hosts the Teleport Auth Service for full permissions.

  Running `tctl` on a Teleport beam

  In some environments, for example on a Teleport beam, Teleport authentication must take place through a local identity file. On a Teleport beam, the identity file is available automatically, and `tctl` reads the file path from the `TELEPORT_IDENTITY_FILE` environment variable.

  When executing `tctl` commands with an identity file, you must pass the `--auth-server` flag to provide the Teleport Auth Service address, which is not included in the identity file. If you provide the Proxy Service address, `tctl` connects to the Proxy Service, which forwards traffic to and from the Teleport Auth Service.

  On a beam, you must use the Proxy Service address, as the Auth Service is not exposed to the public internet. You can do so by using the `TELEPORT_PROXY` environment variable:

  ```
  $ tctl status --auth-server=${TELEPORT_PROXY}
  ```

## Step 1/6. Create service accounts

Teleport requires two types of Google Cloud service accounts:

- **Database Service**: a single service account used by the Teleport Database Service to access Google Cloud and impersonate database user service accounts
- **Database user**: one or more service accounts impersonated per connection to represent database users

For example, in the following steps, we create `teleport-db-service` (Database Service service account) and `spanner-user` (a Database user service account).

### Create the Database Service account

This account is used by the Teleport Database Service to access Google Cloud and impersonate the database user account.

**Google Cloud console**

1. Navigate to **IAM & Admin** → **Service Accounts**.
2. Click **Create Service Account**.
3. Set the name to `teleport-db-service`.
4. Skip optional steps and click **Done**. You will grant permissions later.

**gcloud CLI**

```
$ gcloud iam service-accounts create teleport-db-service --display-name="Teleport Database Service"
```

### Create the database user account

This account represents a database user. Teleport users specify this name when connecting.

**Google Cloud console**

1. Navigate to **IAM & Admin** → **Service Accounts**.
2. Click **Create Service Account**.
3. Set the name to `spanner-user`.
4. Skip optional steps and click **Done**. You will grant permissions later. =

**gcloud CLI**

```
$ gcloud iam service-accounts create spanner-user --display-name="Spanner User"
```

## Step 2/6. Grant permissions

Grant the database user account access to Spanner, then allow the Database Service account to impersonate the database user account.

### Grant Spanner access

**Google Cloud console**

1. Navigate to **Spanner** → **Instances**
2. Select your instance
3. Click **Permissions** → **Add Principal**
4. Enter the `spanner-user` service account
5. Assign **Cloud Spanner Database User**
6. Click **Save**

**gcloud CLI**

```
$ gcloud spanner instances add-iam-policy-binding instance-id \
  --member="serviceAccount:spanner-user@project-id.iam.gserviceaccount.com" \
  --role="roles/spanner.databaseUser"
```

---

CUSTOM SPANNER ROLE

The **Cloud Spanner Database User** role is predefined. You can create custom IAM roles to further restrict access if needed.

---

### Allow service account impersonation

Grant the Database Service account permission to impersonate the database user account.

**Google Cloud console**

1. Navigate to **IAM & Admin** → **Service Accounts**
2. Select `spanner-user`
3. Open the **Permissions** tab
4. Click **Grant Access**
5. Add the `teleport-db-service` account
6. Assign **Service Account Token Creator**
7. Click **Save**

**gcloud CLI**

```
$ gcloud iam service-accounts add-iam-policy-binding \
  spanner-user@project-id.iam.gserviceaccount.com \
  --member="serviceAccount:teleport-db-service@project-id.iam.gserviceaccount.com" \
  --role="roles/iam.serviceAccountTokenCreator"
```

## Step 3/6. Install and configure the Teleport Database Service

To install Teleport binaries on your Linux server, the recommended installation method is the cluster install script. It will select the correct version, edition, and installation mode for your cluster.

1. Remove any existing Teleport binaries on your system:

   ```
   $ sudo rm -f /usr/local/bin/{tsh,teleport,tctl,tbot,fdpass-teleport,teleport-update}
   ```

2. Assign teleport.example.com:443 to your Teleport cluster hostname and port, but not the scheme (https\://).

3. Run your cluster's install script:

   ```
   $ curl "https://teleport.example.com:443/scripts/install.sh" | sudo bash
   ```

The Database Service requires a valid join token to join your Teleport cluster. Run the following `tctl` command and save the token output in `/tmp/token` on the server that will run the Database Service:

```
$ tctl tokens add --type=db --format=text
abcd123-insecure-do-not-use-this
```

Provide the following information and then generate a configuration file for the Teleport Database Service:

- example.teleport.sh:443 The host **and port** of your Teleport Proxy Service or cloud-hosted Teleport Enterprise site.
- project-id The GCP project ID. You can normally see it in the organization view at the top of the GCP dashboard.
- instance-id The name of your Cloud Spanner instance.

```
$ sudo teleport db configure create \
  -o file \
  --name=spanner-example \
  --protocol=spanner \
  --labels=env=dev \
  --token=/tmp/token \
  --uri=spanner.googleapis.com:443 \
  --proxy=example.teleport.sh:443 \
  --gcp-project-id=project-id \
  --gcp-instance-id=instance-id
```

## Step 4/6. Configure GCP credentials

The Teleport Database Service must have credentials for the "teleport-db-service" GCP service account.

If the Teleport Database Service is hosted on a GCE instance, you can [change the attached service account](https://cloud.google.com/compute/docs/instances/change-service-account). For non-GCE deployments of Teleport, we recommend using [workload identity](https://cloud.google.com/iam/docs/workload-identity-federation).

Using service account keys (insecure)

Alternatively, go to that service account's Keys tab and create a new key:

![Service Account Keys](https://website.goteleport.com/_uploads/service_account_keys_2x_084609a658.png)

Make sure to choose JSON format:

![Service Account New Key](https://website.goteleport.com/_uploads/service_account_new_key_2x_a9873dd5d5.png)

Save the file. Set the `GOOGLE_APPLICATION_CREDENTIALS` environment variable to point to the JSON credentials file you downloaded earlier. For example, if you use `systemd` to start `teleport`, then you should edit the service's `EnvironmentFile` to include the env var:

```
$ echo 'GOOGLE_APPLICATION_CREDENTIALS=/path/to/credentials.json' | sudo tee -a /etc/default/teleport
```

---

WARNING

A service account key can be a security risk - we only describe using a key in this guide for simplicity. We do not recommend using service account keys in production. See [authentication](https://cloud.google.com/docs/authentication#service-accounts) in the Google Cloud documentation for more information about service account authentication methods.

---

## Step 5/6. Start the Teleport Database Service

Start the Teleport Database Service. The instructions depend on how you installed the Teleport Database Service and whether your system supports systemd:

**Package Manager**

Configure the Teleport Database Service to start automatically when the host boots up by creating a systemd service for it. On the host where you will run the Teleport Database Service, enable and start Teleport:

```
$ sudo systemctl enable teleport
$ sudo systemctl start teleport
```

You can check the status of the Teleport Database Service with `systemctl status teleport` and view its logs with `journalctl -fu teleport`.

**TAR Archive**

Configure the Teleport Database Service to start automatically when the host boots up by creating a systemd service for it. On the host where you will run the Teleport Database Service, create a systemd service configuration for Teleport, enable the Teleport service, and start Teleport:

```
$ sudo teleport install systemd -o /etc/systemd/system/teleport.service
$ sudo systemctl enable teleport
$ sudo systemctl start teleport
```

You can check the status of the Teleport Database Service with `systemctl status teleport` and view its logs with `journalctl -fu teleport`.

**No systemd**

On the host where you will run the Teleport Database Service, start Teleport:

```
$ sudo teleport start --config=/etc/teleport.yaml
```

Teleport runs in the foreground and outputs logs for the services it is running.

## Step 6/6. Connect using the service account

In this step, you will create a Teleport user with access to the Spanner database, connect using the database user service account, and optionally remove stored credentials when you are done.

---

TIP

To modify an existing user to provide access to the Database Service, see [Database Access Controls](https://goteleport.com/docs/enroll-resources/database-access/rbac.md)

---

**Teleport Community Edition**

Create a local Teleport user with the built-in `access` role:

```
$ tctl users add \
  --roles=access \
  --db-users="*" \
  --db-names="*" \
  alice
```

**Teleport Enterprise/Enterprise Cloud**

Create a local Teleport user with the built-in `access` and `requester` roles:

```
$ tctl users add \
  --roles=access,requester \
  --db-users="*" \
  --db-names="*" \
  alice
```

| Flag         | Description                                                                                                                              |
| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------- |
| `--roles`    | List of roles to assign to the user. The builtin `access` role allows them to connect to any database server registered with Teleport.   |
| `--db-users` | List of database usernames the user will be allowed to use when connecting to the databases. A wildcard allows any user.                 |
| `--db-names` | List of logical databases (aka schemas) the user will be allowed to connect to within a database server. A wildcard allows any database. |

---

WARNING

Database names are only enforced for PostgreSQL, MongoDB, and Cloud Spanner databases.

---

For more detailed information about database access controls and how to restrict access see [RBAC](https://goteleport.com/docs/enroll-resources/database-access/rbac.md) documentation.

Log in to your Teleport cluster as the new user that you just created:

```
$ tsh login --proxy=example.teleport.sh --user=example-user
```

Connect using the service account name (without the domain suffix): (Note: `--db-name` here refers to the specific database ID within your Spanner instance.)

```
$ tsh db connect --db-user=spanner-user --db-name=database-name spanner-example
```

You should now have an authenticated connection using the impersonated service account.

To remove credentials:

```
$ tsh db logout spanner-example
```

To remove all database credentials:

```
$ tsh db logout
```

## Troubleshooting

### Could not find default credentials

This error can come from either your client application or Teleport.

For a client application, ensure that you disable GCP credential loading. Your client should not attempt to load credentials because GCP credentials will be provided by the Teleport Database Service.

If you see the credentials error message in the Teleport Database Service logs (at DEBUG log level), then the Teleport Database Service does not have GCP credentials configured correctly.

If you are using a service account key, then ensure that the environment variable `GOOGLE_APPLICATION_CREDENTIALS=/path/to/credentials.json` is set and restart your Teleport Database Service to ensure that the env var is available to `teleport`. For example, if your Teleport Database Service runs as a `systemd` service:

```
$ echo 'GOOGLE_APPLICATION_CREDENTIALS=/path/to/credentials.json' | sudo tee -a /etc/default/teleport
$ sudo systemctl restart teleport
```

See [authentication](https://cloud.google.com/docs/authentication#service-accounts) in the Google Cloud documentation for more information about service account authentication methods.

## Next steps

- Learn how to [restrict access](https://goteleport.com/docs/enroll-resources/database-access/rbac.md) to certain users and databases.

* View the [High Availability (HA)](https://goteleport.com/docs/installation/agents/high-availability.md) guide.

- Take a look at the [configuration reference](https://goteleport.com/docs/reference/deployment/config.md#database-service).

* Explore the [`db` resource reference](https://goteleport.com/docs/reference/infrastructure-as-code/teleport-resources/database-v3.md)

- See the full CLI [reference](https://goteleport.com/docs/enroll-resources/database-access/reference/cli.md).

* Learn how to [connect with a GUI client](https://goteleport.com/docs/connect-your-client/third-party/gui-clients.md#cloud-spanner-datagrip).
* Learn more about [service account authentication](https://cloud.google.com/docs/authentication#service-accounts).
