Database Access with AlloyDB
Teleport can provide secure access to AlloyDB via the Teleport Database Service. This allows for fine-grained access control through Teleport's RBAC.
In this guide, you will:
- Configure your AlloyDB database with a service account.
- Add the database to your Teleport cluster.
- 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.
Prerequisites
-
A running Teleport cluster. If you want to get started with Teleport, sign up for a free trial or set up a demo environment.
-
The
tctlandtshclients.Installing
tctlandtshclients-
Determine the version of your Teleport cluster. The
tctlandtshclients must be at most one major version behind your Teleport cluster version. Send a GET request to the Proxy Service at/v1/webapi/findand 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:443TELEPORT_VERSION="$(curl -s https://$TELEPORT_DOMAIN/v1/webapi/find | jq -r '.server_version')" -
Follow the instructions for your platform to install
tctlandtshclients:- Mac
- Windows - Powershell
- Linux
Download the signed macOS .pkg installer for Teleport, which includes the
tctlandtshclients:curl -O https://cdn.teleport.dev/teleport-${TELEPORT_VERSION?}.pkgIn Finder double-click the
pkgfile to begin installation.dangerUsing 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.
curl.exe -O https://cdn.teleport.dev/teleport-v${TELEPORT_VERSION?}-windows-amd64-bin.zipUnzip 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.
All of the Teleport binaries in Linux installations include the
tctlandtshclients. For more options (including RPM/DEB packages and downloads for i386/ARM/ARM64) see our installation page.curl -O https://cdn.teleport.dev/teleport-v${TELEPORT_VERSION?}-linux-amd64-bin.tar.gztar -xzf teleport-v${TELEPORT_VERSION?}-linux-amd64-bin.tar.gzcd teleportsudo ./installTeleport binaries have been copied to /usr/local/bin
-
- Google Cloud account with an AlloyDB cluster and instance deployed, configured for IAM database authentication.
psqlinstalled and in your systemPATH.- A host (e.g., a Compute Engine instance) to 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 runtctlcommands 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:If you can connect to the cluster and run thetsh login --proxy=teleport.example.com --user=email@example.comtctl statusCluster teleport.example.com
Version 19.0.0-dev
CA pin sha256:abdc1245efgh5678abdc1245efgh5678abdc1245efgh5678abdc1245efgh5678
tctl statuscommand, you can use your current credentials to run subsequenttctlcommands from your workstation. If you host your own Teleport cluster, you can also runtctlcommands on the computer that hosts the Teleport Auth Service for full permissions.
Step 1/4: Configure GCP IAM and database user
You need two service accounts:
teleport-db-service: used by the Teleport Database Service to access AlloyDB metadata and generate tokens.alloydb-user: used by end-users to authenticate to the database.
Create the Database Service account
- Google Cloud Console
- gcloud CLI
Go to Service Accounts
and create a service account named teleport-db-service.
Assign the predefined roles/alloydb.client role.
Set project-id to your GCP project ID.
gcloud iam service-accounts create teleport-db-service \ --display-name="Teleport Database Service"gcloud projects add-iam-policy-binding project-id \ --member="serviceAccount:teleport-db-service@project-id.iam.gserviceaccount.com" \ --role="roles/alloydb.client"
Create the database user account
If you already have a GCP service account for database access with the required roles, you can use it instead.
- Google Cloud Console
- gcloud CLI
Go to Service Accounts
and create a service account named alloydb-user.
Assign these roles:
roles/alloydb.databaseUserroles/alloydb.clientroles/serviceusage.serviceUsageConsumer
Then, on the alloydb-user overview page, go to the "Principals with Access" tab, click "Grant Access", and add teleport-db-service with the Service Account Token Creator role.
gcloud iam service-accounts create alloydb-user \ --display-name="AlloyDB User"for role in roles/alloydb.databaseUser roles/alloydb.client roles/serviceusage.serviceUsageConsumer;do \ gcloud projects add-iam-policy-binding project-id \ --member="serviceAccount:alloydb-user@project-id.iam.gserviceaccount.com" \ --role="$role"; donegcloud iam service-accounts add-iam-policy-binding \ alloydb-user@project-id.iam.gserviceaccount.com \ --member="serviceAccount:teleport-db-service@project-id.iam.gserviceaccount.com" \ --role="roles/iam.serviceAccountTokenCreator"
Add the IAM database user to AlloyDB
Skip this if your AlloyDB instance already has an IAM user for this service account.
Ensure IAM authentication is enabled on your instance (the alloydb.iam_authentication flag must be set).
Go to the Users page of your AlloyDB instance, click "Add User Account", choose "Cloud IAM" authentication, and add alloydb-user.
Step 2/4: Set up the Database Service host
If you already have a host running the Teleport Database Service with the teleport-db-service credentials, skip to Step 3.
Create a GCE instance and attach the teleport-db-service service account in the "Identity and API access" section.
Attaching the service account to an existing GCE instance
- Google Cloud Console
- gcloud CLI
- Navigate to VM instances and open your instance.
- Stop the instance.
- Edit the instance, find Service account under Identity and API access, and select
teleport-db-service. - Save and restart.
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
The instance must be stopped before modifying the service account
gcloud compute instances stop instance-name --zone=zoneAttach the service account with the 'cloud-platform' scope to allow IAM roles
to govern all API access
gcloud compute instances set-service-account instance-name \ --service-account=teleport-db-service@project-id.iam.gserviceaccount.com \ --scopes=[https://www.googleapis.com/auth/cloud-platform](https://www.googleapis.com/auth/cloud-platform) \ --zone=zonegcloud compute instances start instance-name --zone=zone
Verify the instance is running with the correct service account and scopes:
gcloud compute instances describe instance-name --zone=zone \ --format="table(status,serviceAccounts[0].email,serviceAccounts[0].scopes.list())"
If running on a non-GCE host, use workload identity federation to provide credentials.
Using service account keys (not recommended for production)
Create a JSON key for the teleport-db-service account and set the environment variable:
echo 'GOOGLE_APPLICATION_CREDENTIALS=/path/to/credentials.json' | \sudo tee -a /etc/default/teleport
Service account keys are a security risk. Use workload identity or attached service accounts in production. See Google Cloud authentication docs for details.
Step 3/4: Configure and start Teleport
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.
-
Assign teleport.example.com:443 to your Teleport cluster hostname and port, but not the scheme (https://).
-
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=textabcd123-insecure-do-not-use-this
Replace teleport.example.com:443 with your Teleport Proxy address and connection-uri with your AlloyDB connection URI (format: projects/PROJECT/locations/REGION/clusters/CLUSTER/instances/INSTANCE, found on the instance details page).
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
By default, Teleport uses the private AlloyDB endpoint.
To use public or PSC endpoints, set endpoint_type in the config:
db_service:
resources:
- name: alloydb
protocol: postgres
uri: alloydb://projects/PROJECT/locations/REGION/clusters/CLUSTER/instances/INSTANCE
gcp:
alloydb:
endpoint_type: public # private | public | psc
Using a dynamic resource instead
Create alloydb.yaml:
kind: db
version: v3
metadata:
name: alloydb-dynamic
labels:
env: dev
spec:
protocol: "postgres"
uri: "alloydb://connection-uri"
gcp:
alloydb:
endpoint_type: private
Apply it:
tctl create -f alloydb.yaml
Start the 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
- TAR Archive
On the host where you will run the Teleport Database Service, enable and start Teleport:
sudo systemctl enable teleportsudo systemctl start teleport
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.servicesudo systemctl enable teleportsudo 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 4/4: Connect
To modify an existing user to provide access to the Database Service, see Database Access Controls
- Teleport Community Edition
- Teleport Enterprise/Enterprise Cloud
Create a local Teleport user with the built-in access role:
tctl users add \ --roles=access \ --db-users="*" \ --db-names="*" \ alice
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. |
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 documentation.
Log in and list databases:
tsh login --proxy=teleport.example.com --user=alicetsh db lsName Description Labels
------- ----------- -------
alloydb GCP AlloyDB env=dev
Connect using the service account name (minus .gserviceaccount.com):
tsh db connect --db-user=alloydb-user@project-id.iam --db-name=postgres alloydb
From version 17.1, you can also
connect via the Web UI.
To log out:
tsh db logout alloydbOr for all databases:
tsh db logout
Optional: least-privilege IAM roles
For tighter security, replace the predefined roles with custom roles containing only the required permissions.
For teleport-db-service:
alloydb.clusters.generateClientCertificatealloydb.instances.connectiam.serviceAccounts.getAccessToken(replaces the broader "Service Account Token Creator" role)
For alloydb-user:
alloydb.instances.connectalloydb.users.loginserviceusage.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/teleportsudo systemctl restart teleport
See authentication 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
then tsh db connect will automatically start a local proxy for every
connection.
Alternatively, you can connect via
Teleport Connect
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
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 postgrespsql: 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 to certain users and databases.
- View the High Availability (HA) guide.
- Take a look at the YAML configuration reference.
- See the full CLI reference.
- Learn more about IAM authentication for AlloyDB.
- Learn more about service account authentication in Google Cloud.
- Learn more about AlloyDB Auth Proxy permissions.