# Database Access with AlloyDB

Teleport can provide secure access to AlloyDB 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 AlloyDB 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 AlloyDB. 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.

![Teleport Architecture for AlloyDB Access](/docs/assets/images/architecture-4d2cc43d241a8934656315deb2bb278b.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:

     ```
     $ TELEPORT_DOMAIN=teleport.example.com:443
     $ TELEPORT_VERSION="$(curl -s https://$TELEPORT_DOMAIN/v1/webapi/find | jq -r '.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.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
     ```

* Google Cloud account with an AlloyDB cluster and instance deployed. Ensure that your instance is configured to use [IAM database authentication](https://cloud.google.com/alloydb/docs/database-users/manage-iam-auth).
* Command-line client `psql` installed and added to your system's `PATH` environment variable.
* A host, e.g., a Compute Engine instance, where you will run the Teleport Database Service.
* 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  18.7.3
  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.

## Step 1/5: Configure GCP IAM

### IAM setup: roles for the database user and database service

To grant Teleport access to your AlloyDB instances, you need to create two service accounts:

- `teleport-db-service`: for the Teleport Database Service to access AlloyDB metadata.
- `alloydb-user`: for end-users to authenticate to the database.

### Create a service account for the Teleport Database Service

A GCP service account will be used by the Teleport Database Service to create ephemeral access tokens for *other* GCP service accounts when it's acting on the behalf of authorized Teleport users.

Go to the [Service Accounts](https://console.cloud.google.com/iam-admin/serviceaccounts) page and create a service account:

![Create System Service Account](/docs/assets/images/create-system-service-account-2845f1e82deeb8a2f975f15316f7438b.png)

The Teleport Database Service needs permissions to call Google Cloud APIs to fetch database connection information and generate client certificates.

Assign the predefined [`roles/alloydb.client` (Cloud AlloyDB Client)](https://cloud.google.com/alloydb/docs/reference/iam-roles-permissions) role to the `teleport-db-service` service account. This role grants the necessary permissions.

![Grant permissions to user Service Account](/docs/assets/images/system-service-account-permissions-2b116e631890e12d09e07b3bd2e66bef.png)

### Create a service account for a database user

---

NOTE

If you already have a standard GCP service account for database access, you can use it instead of creating a new one. Ensure it has the required permissions listed below.

---

Teleport uses service accounts to connect to AlloyDB databases.

Go to the IAM & Admin [Service Accounts](https://console.cloud.google.com/iam-admin/serviceaccounts) page and create a new service account named `alloydb-user`:

![Create User Service Account](/docs/assets/images/create-user-service-account-38cc4e6c4352acef8f8cee889cbeecfc.png)

Click "Create and continue".

Assign the following [predefined roles](https://cloud.google.com/alloydb/docs/reference/iam-roles-permissions) to the `alloydb-user` service account:

- Cloud AlloyDB Database User (`roles/alloydb.databaseUser`)
- Cloud AlloyDB Client (`roles/alloydb.client`)
- [Service Usage Consumer (`roles/serviceusage.serviceUsageConsumer`)](https://cloud.google.com/service-usage/docs/access-control#serviceusage.serviceusageconsumer)

![Grant permissions to user Service Account](/docs/assets/images/user-service-account-permissions-a6976116d81337dfaa4443a85d1a4f28.png)

### Grant access to the service account

The Teleport Database Service must be able to impersonate this service account. Navigate to the `alloydb-user` service account overview page and select the "Principals with Access" tab:

![Select Principals with Access Tab](/docs/assets/images/user-service-account-principals-with-access-8f6d638b49f8cbfbfc2f09dd40e19c29.png)

Click "Grant Access" and add the `teleport-db-service` principal ID. Select the "Service Account Token Creator" role and save the change:

![Grant Service Account Token Creator to Database Service](/docs/assets/images/user-service-account-grant-access-7aae4d5cb9590639c46401d16c882088.png)

## Step 2/5: Database configuration

Enabling IAM Authentication

Teleport uses [IAM database authentication](https://cloud.google.com/alloydb/docs/database-users/manage-iam-auth) with AlloyDB instances.

Ensure that your instance is configured to use IAM authentication. Navigate to your instance settings and check the presence of the `alloydb.iam_authentication` flag under Advanced Configuration Options section.

![Enable IAM Authentication](/docs/assets/images/flag-iam-authentication-on-009c618a0a40ca4c35049e08307a275c.png)

### Create a database user

---

NOTE

If your AlloyDB instance already has an IAM user configured for your designated service account, you can skip this step.

---

Go to the Users page of your AlloyDB instance and add a new user account. In the sidebar, choose "Cloud IAM" authentication type and add the `alloydb-user` service account that you created earlier.

![Add AlloyDB User Account](/docs/assets/images/add-user-account-f7c050311659436446c64ad1268762fc.png)

Press "Add" and your Users table should look similar to this:

![AlloyDB User Accounts Table](/docs/assets/images/user-account-added-d69952499f003af3835a4bb80fb0f307.png)

## Step 3/5: Create a host for the Database Service

---

NOTE

If you already have a host running the Teleport Database Service, you can skip this step. Just ensure that the host is configured with the `teleport-db-service` service account's credentials, either by attaching the service account (for GCE) or through workload identity.

---

Create a Google Compute Engine (GCE) instance where you will run the Teleport Database Service.

When creating the instance, in the "Security" section, attach the `teleport-db-service` service account you created earlier. This allows the Teleport Database Service to authenticate with Google Cloud APIs.

Attaching a service account to an existing GCE instance

**Google Cloud Console**

If you have an existing GCE instance, you can attach the service account through the Google Cloud Console.

1. Navigate to the [VM instances](https://console.cloud.google.com/compute/instances) page and open your instance.
2. Stop the instance. Wait for it to fully stop.
3. Edit the instance details.
4. Find the **Service account** dropdown in the **Identity and API access** section.
5. Select the `teleport-db-service` service account.
6. Save the changes and restart the instance.

**gcloud CLI**

If you have an existing GCE instance, you can attach the service account using the `gcloud` command-line tool.

Set the variables:

- instance-name instance name
- zone instance zone
- project-id GCP project ID

First, stop the instance:

```
$ gcloud compute instances stop instance-name --zone=zone
```

Then, set the service account:

```
$ gcloud compute instances set-service-account instance-name                 \
    --service-account=teleport-db-service@project-id.iam.gserviceaccount.com \
    --zone=zone
```

Restart the instance:

```
$ gcloud compute instances start instance-name --zone=zone
```

Verify the instance is now running with the specified service account:

```
$ gcloud compute instances describe instance-name --zone=zone \
   --format="yaml(status,serviceAccounts)"
```

If you are running the Teleport Database Service on a different host, you will need to provide credentials to the service. 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.

Make sure to choose JSON format.

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 4/5: Configure Teleport

### Install the Teleport Database Service

To install a Teleport Agent 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. Assign teleport.example.com:443 to your Teleport cluster hostname and port, but not the scheme (https\://).

2. Run your cluster's install script:

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

### Create a join token

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
```

### Configure and start the Database Service

In the command below, replace teleport.example.com:443 with the host and port of your Teleport Proxy Service or Enterprise Cloud site, and replace connection-uri with your AlloyDB connection URI.

The connection URI has the format `projects/PROJECT/locations/REGION/clusters/CLUSTER/instances/INSTANCE`. You can copy it from the AlloyDB instance details page in the Google Cloud console.

![AlloyDB Connection URI](/docs/assets/images/connection-uri-bd28375d3047632a4c28248c6cdc8b07.png)

Run the command as follows. Make sure to include the mandatory `alloydb://` prefix in the specified URI.

```
$ sudo teleport db configure create \
   -o file \
   --name=alloydb \
   --protocol=postgres \
   --labels=env=dev \
   --token=/tmp/token \
   --proxy=teleport.example.com:443  \
   --uri=alloydb://connection-uri
```

This command will generate a Teleport Database Service configuration file and save it to `/etc/teleport.yaml`.

---

CHOOSE HOW TELEPORT CONNECTS TO ALLOYDB

By default, Teleport uses [*private*](https://cloud.google.com/alloydb/docs/about-private-services-access) AlloyDB endpoint. To change this to either [public](https://cloud.google.com/alloydb/docs/connect-public-ip) or [PSC](https://cloud.google.com/alloydb/docs/about-private-service-connect) endpoints, update the `endpoint_type` field:

```
db_service:
  resources:
    - name: alloydb
      protocol: postgres
      uri: alloydb://projects/PROJECT/locations/REGION/clusters/CLUSTER/instances/INSTANCE
      gcp:
        alloydb:
          # one of: private | public | psc (default: private)
          endpoint_type: private
      static_labels:
        env: dev

```

---

Dynamic resource

As an alternative to configuring the database in `teleport.yaml`, you can create a dynamic database resource. This allows you to add or update databases without restarting the Database Service.

Create a file named `alloydb.yaml` with the following content:

```
kind: db
version: v3
metadata:
  name: alloydb-dynamic
  labels:
    env: dev
spec:
  protocol: "postgres"
  uri: "alloydb://connection-uri"
  gcp:
    alloydb:
      # one of: private | public | psc (default: private)
      endpoint_type: private

```

Replace connection-uri with your AlloyDB connection URI.

Create the resource:

```
$ tctl create -f alloydb.yaml
```

Finally, start the Teleport Database Service:

Configure the Teleport Database Service to start automatically when the host boots up by creating a systemd service for it. The instructions depend on how you installed the Teleport Database Service.

**Package Manager**

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

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

**TAR Archive**

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`.

## Step 5/5: Connect to your database

### Grant access to the database

---

NOTE

The following commands create a new Teleport user and role. If you have an existing Teleport user and a role that grants access to resources with the `env: dev` label, you can skip these steps.

---

---

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.

### Connect

Once the Database Service has joined the cluster, log in to see the available databases:

```
$ tsh login --proxy=teleport.example.com --user=alice
$ tsh db ls
Name    Description Labels
------- ----------- -------
alloydb GCP AlloyDB env=dev
```

---

NOTE

You will only be able to see databases that your Teleport role has access to. See our [RBAC](https://goteleport.com/docs/enroll-resources/database-access/rbac.md) guide for more details.

---

When connecting to the database, use the name of the database's service account that you added as an IAM database user earlier, minus the `.gserviceaccount.com` suffix. The database user name is shown on the Users page of your AlloyDB instance.

In the command below, replace project-id with your Google Cloud project ID. Retrieve credentials for the `alloydb` example database and connect to it:

```
$ tsh db connect --db-user=alloydb-user@project-id.iam --db-name=postgres alloydb
```

---

TIP

Starting from version `17.1`, you can now [access your PostgreSQL databases using the Web UI.](https://goteleport.com/docs/connect-your-client/teleport-clients/web-ui.md#starting-a-database-session)

---

To log out of the database and remove credentials:

```
Remove credentials for a particular database instance:
$ tsh db logout alloydb
Or remove credentials for all databases:
$ tsh db logout
```

## Optional: least-privilege access

When possible, enforce least-privilege by defining custom IAM roles that grant only the required permissions.

### Custom role for the Teleport Database Service

The Teleport Database Service, running as the `teleport-db-service` service account, needs permissions to access the AlloyDB instance.

Create a custom role with the following permissions:

```
# Used to generate client certificate
alloydb.clusters.generateClientCertificate
# Used to fetch connection information
alloydb.instances.connect

```

For impersonating the `alloydb-user` service account, the built-in "Service Account Token Creator" IAM role is broader than necessary. To restrict permissions for that service account, create a custom role that includes only:

```
iam.serviceAccounts.getAccessToken

```

### Custom role for the database user

The `alloydb-user` service account used for database access requires permissions to connect to the instance and authenticate as a database user. Create a custom role with:

```
alloydb.instances.connect
alloydb.users.login
serviceusage.services.use

```

## 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.

### Unable to cancel a query

If you use a PostgreSQL cli client like `psql`, and you try to cancel a query with `Ctrl+C`, but it doesn't cancel the query, then you need to connect using a tsh local proxy instead. When `psql` cancels a query, it establishes a new connection without TLS certificates, however Teleport requires TLS certificates not only for authentication, but also to route database connections.

If you [enable TLS Routing in Teleport](https://goteleport.com/docs/zero-trust-access/deploy-a-cluster/tls-routing.md) then `tsh db connect` will automatically start a local proxy for every connection. Alternatively, you can connect via [Teleport Connect](https://goteleport.com/docs/connect-your-client/teleport-clients/teleport-connect.md) which also uses a local proxy. Otherwise, you need to start a tsh local proxy manually using `tsh proxy db` and connect via the local proxy.

If you have already started a long-running query in a `psql` session that you cannot cancel with `Ctrl+C`, you can start a new client session to cancel that query manually:

First, find the query's process identifier (PID):

```
SELECT pid,usename,backend_start,query FROM pg_stat_activity WHERE state = 'active';

```

Next, gracefully cancel the query using its PID. This will send a SIGINT signal to the postgres backend process for that query:

```
SELECT pg_cancel_backend(<PID>);

```

You should always try to gracefully terminate a query first, but if graceful cancellation is taking too long, then you can forcefully terminate the query instead. This will send a SIGTERM signal to the postgres backend process for that query:

```
SELECT pg_terminate_backend(<PID>);

```

See the PostgreSQL documentation on [admin functions](https://www.postgresql.org/docs/current/functions-admin.html#functions-admin-signal) for more information about the `pg_cancel_backend` and `pg_terminate_backend` functions.

### SSL SYSCALL error

You may encounter the following error when your local `psql` is not compatible with newer versions of OpenSSL:

```
$ tsh db connect --db-user postgres --db-name postgres postgres
psql: error: connection to server at "localhost" (::1), port 12345 failed: Connection refused
    Is the server running on that host and accepting TCP/IP connections?
connection to server at "localhost" (127.0.0.1), port 12345 failed: SSL SYSCALL error: Undefined error: 0
```

Please upgrade your local `psql` to the latest version.

## 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/enroll-resources/agents/high-availability.md) guide.

- Take a look at the YAML configuration [reference](https://goteleport.com/docs/enroll-resources/database-access/reference/configuration.md).

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

- Learn more about [managing IAM authentication](https://cloud.google.com/alloydb/docs/database-users/manage-iam-auth) for AlloyDB.

* Learn more about [authenticating as a service account](https://cloud.google.com/docs/authentication#service-accounts) in Google Cloud.

- Learn more about AlloyDB [Auth Proxy](https://cloud.google.com/alloydb/docs/auth-proxy/connect#required-iam-permissions).
