# Database Access with Cloud SQL for MySQL

Teleport can provide secure access to MySQL on Google Cloud SQL 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 MySQL on Google Cloud SQL 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 MySQL. 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 SQL Access](/docs/assets/images/cloudsql_selfhosted-d65faab984c4e259628374696047b208.png)

**Cloud-Hosted**

![Cloud-Hosted Teleport Architecture for Cloud SQL Access](/docs/assets/images/cloudsql_cloud-0d10000ea7aac3c68ebebb0417a577f6.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
* 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  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.

## Step 1/9. 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.

### Create a service account

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

![Create Service Account](/docs/assets/images/service-account-db-service@2x-894c28edfe0f2f1477bc18d723688723.png)

### (Optional) Grant permissions

The Teleport Database Service needs permissions to automatically download your Cloud SQL instance's root CA certificate and to generate an ephemeral client certificate.

If you intend to download the CA certificate manually and your Cloud SQL instance SSL mode is not "require trusted client certificates", then you can skip this step.

Otherwise, in the second step of the service account creation dialogue, assign the service account the pre-defined GCP IAM role "Cloud SQL Client", then click "Done".

Cloud SQL Client permissions

The "Cloud SQL Client" role has the following permissions:

```
# Used to auto-download the instance's root CA certificate and check SSL mode.
cloudsql.instances.get
# Used to generate an ephemeral client certificate
cloudsql.instances.connect

```

If you only need one of these permissions, you can define and assign a custom IAM role to the service account instead.

### (Optional) Grant permission to check user type

When users connect to the Cloud SQL database via Teleport, they must specify the name of the service account that they intend to use as a database user. They can use either the short name or the full email of the service account, e.g. if the account email is `cloudsql-user@project.iam.gserviceaccount.com` then they can use "cloudsql-user" instead of the full email.

However, if they use the short name of the service account, then Teleport will need permissions to determine the kind of authentication that it should use: IAM auth or legacy one-time password auth. If it does not have this permission, then it will attempt to use a one-time password by default. The following permission is required to support IAM auth with the short name of a service account:

```
# Used to check database user type.
cloudsql.users.get

```

The pre-defined "Cloud SQL Viewer" role has this permission, but also has other permissions that are not needed. Define and bind a custom role to the service account to follow the principle of least privilege.

---

NOTE

Support for legacy one-time password authentication will be deprecated. If you are following this guide and have already set up Teleport prior to the introduction of support for IAM database user authentication, then you should configure your database users to use IAM auth as described in this guide.

---

## Step 2/9. Create a service account for a database user

Teleport uses service accounts to connect to Cloud SQL databases.

### Create a service account

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

![Create Service Account](/docs/assets/images/service-account-db@2x-459b8d9fa3326f96869f90e028420bc7.png)

Click "Create and continue".

### Grant permissions

On the second step grant this service account the "Cloud SQL Instance User" role which will allow it to connect to Cloud SQL instances using an IAM token for authentication:

![Grant Cloud SQL Instance User to Service Account](/docs/assets/images/service-account-db-grant@2x-58b85a4c271e1f1cd71836a44da2c5fc.png)

Click "Done".

### Grant access to the service account

The Teleport Database Service must be able to impersonate this service account. Navigate to the "cloudsql-user" service account overview page and select the "permissions" tab:

![Select Service Account Permissions Tab](/docs/assets/images/service-account-permissions-tab@2x-9f2a3c83b688fe92f06ab9f3ac87f334.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/grant-token-creator@2x-c4fcd3812bc55d11b21b48e6d5112775.png)

---

SERVICE ACCOUNT PERMISSIONS

The "Service Account Token Creator" IAM role includes more permissions than the Teleport Database Service needs. To further restrict the service account, you can create a role that includes only the following permission:

```
# Used to generate IAM auth tokens when connecting to a database instance.
iam.serviceAccounts.getAccessToken

```

---

## Step 3/9. Configure your Cloud SQL database

### Enable Cloud SQL IAM authentication

Teleport uses [IAM authentication](https://cloud.google.com/sql/docs/mysql/iam-authentication) with Cloud SQL MySQL instances.

If you're [creating](https://console.cloud.google.com/sql/choose-instance-engine) a new MySQL instance, make sure to add the `cloudsql.iam_authentication` database flag under "Customize your instance / Flags" section:

![Enable IAM Authentication](/docs/assets/images/iam-new-instance@2x-6445ba0d76c80d0bea5945eccc591065.png)

To check whether IAM authentication is enabled for an existing Cloud SQL instance, look for the flag on the Configuration panel on the instance's Overview page:

![Check IAM Authentication](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAigAAACgCAMAAAARr2crAAABQmlDQ1BJQ0MgUHJvZmlsZQAAKJFjYGASSCwoyGFhYGDIzSspCnJ3UoiIjFJgf8rAwsDGIMygwqCfmFxc4BgQ4ANUwgCjUcG3awyMIPqyLsis3oc1Ogdct6wp3l3+cGmvkzamehTAlZJanAyk/wBxSnJBUQkDA2MCkK1cXlIAYrcA2SJFQEcB2TNA7HQIew2InQRhHwCrCQlyBrKvANkCyRmJKUD2EyBbJwlJPB2JDbUX7AYfdwUPlyAFE28CjiUVlKRWlIBo5/yCyqLM9IwSBUdgCKUqeOYl6+koGBkYGTIwgMIbovqzGDgcGcVOIcQqrzMwWAQCGTEIsZC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5gAAAAASUVORK5CYII=)

If it isn't enabled, you can add this flag using the "Edit configuration" dialog at the bottom of the Configuration panel. Changing this setting may require a database instance reboot.

### (Optional) SSL mode "require trusted client certificates"

When using Cloud SQL MySQL with "require trusted client certificates" enabled, Teleport connects to the database's Cloud SQL Proxy port `3307` instead of the default `3306` as the default Cloud SQL MySQL listener does not trust generated ephemeral certificates. For this reason, you should make sure to allow port `3307` when using "require trusted client certificates".

---

NOTE

The "require trusted client certificates" SSL mode only forces the client (Teleport) to provide a trusted client certificate. Teleport will always connect to the database over encrypted TLS regardless of the instance's SSL mode setting.

---

### Create a database user

Now go back to the Users page of your Cloud SQL instance and add a new user account. In the sidebar, choose "Cloud IAM" authentication type and add the "cloudsql-user" service account you created in [the second step](#step-29-create-a-service-account-for-a-database-user):

![Add Cloud SQL User Account](/docs/assets/images/add-user-account-mysql@2x-1fbdcadb88bbcbfc6472ce6d57691f2c.png)

Press "Add". See [Creating and managing IAM users](https://cloud.google.com/sql/docs/mysql/add-manage-iam-users) in Google Cloud documentation for more info.

## Step 4/9. Install 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.

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

## Step 5/9. Configure the Teleport Database Service

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

### (Optional) Download the Cloud SQL CA certificate

The Cloud SQL instance's root CA certificate is required so that the Teleport Database Service can validate the certificate presented by the database instance.

The Teleport Database Service can automatically download the instance's root CA certificate if it is granted the "cloudsql.instances.get" permission.

Alternatively, you can download the instance's CA certificate file from the "Connections" tab under the "Security" section:

![Instance Root Certificate](/docs/assets/images/instance-root-ca@2x-e110df930fce286de4f38e8d2007dc23.png)

### Generate Teleport config

**Configure Teleport With Automatic CA Download**

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 Enterprise Cloud site
- public-ip The Cloud SQL instance public IP address. The address can be found on the "Connect to this instance" panel on the "Overview" page in the Cloud SQL instance's dashboard.
- 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 SQL instance.

```
$ sudo teleport db configure create \
   -o file \
   --name=cloudsql \
   --protocol=mysql \
   --labels=env=dev \
   --token=/tmp/token \
   --proxy=example.teleport.sh:443  \
   --uri=public-ip:3306 \
   --gcp-project-id=project-id \
   --gcp-instance-id=instance-id 
```

**Configure Teleport With Manual CA Download**

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 Enterprise Cloud site
- public-ip The Cloud SQL instance public IP address. The address can be found on the "Connect to this instance" panel on the "Overview" page in the Cloud SQL instance's dashboard.
- 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 SQL instance.
- /path/to/cloudsql/instance/server-ca.pem The path to the Cloud SQL instance root CA certificate

```
$ sudo teleport db configure create \
   -o file \
   --name=cloudsql \
   --protocol=mysql \
   --labels=env=dev \
   --token=/tmp/token \
   --proxy=example.teleport.sh:443  \
   --uri=public-ip:3306 \
   --gcp-project-id=project-id \
   --gcp-instance-id=instance-id \
   --ca-cert-file=/path/to/cloudsql/instance/server-ca.pem 
```

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

## Step 6/9. 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](/docs/assets/images/service-account-keys@2x-0a3270370e86e9a93ce51fb7b6174d2d.png)

Make sure to choose JSON format:

![Service Account New Key](/docs/assets/images/service-account-new-key@2x-ebf26eda3b9625e0571a1b53378fe640.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 7/9. 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 8/9. Create a Teleport user

---

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.

## Step 9/9. Connect

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

**Self-Hosted**

```
$ tsh login --proxy=teleport.example.com --user=alice
$ tsh db ls
Name     Description         Labels
-------- ------------------- --------
cloudsql GCP Cloud SQL MySQL env=dev
```

**Teleport Enterprise (cloud-hosted)**

```
$ tsh login --proxy=mytenant.teleport.sh --user=alice
$ tsh db ls
Name     Description         Labels
-------- ------------------- --------
cloudsql GCP Cloud SQL MySQL 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 either the database user name or the service account's Email ID. Both the user name and the service account's Email ID are shown on the Users page of your Cloud SQL instance. Retrieve credentials for the "cloudsql" example database and connect to it, assigning project-id to your Google Cloud project ID:

```
Connect with the short name of the database user service account:
$ tsh db connect --db-user=cloudsql-user --db-name=mysql cloudsql
Or connect the full email ID:
$ tsh db connect --db-user=cloudsql-user@project-id.iam.gserviceaccount.com --db-name=mysql cloudsql
```

---

TIP

You can also [access your MySQL 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 cloudsql
Or remove credentials for all databases:
$ tsh db logout
```

## Troubleshooting

### Error when connecting to a replica instance

You may encounter the following error when connecting to a replica instance:

```
$ tsh db connect --db-user=cloudsql-user --db-name=test cloudsql-replica
ERROR 1105 (HY000): Could not update Cloud SQL user "<username>" password:

  The requested operation is not valid for a replica instance.

...
```

Connecting as built-in database users with passwords are not supported for Cloud SQL replica instances. Please follow this guide to use IAM authentication instead.

### 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/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 [authenticating as a service account](https://cloud.google.com/docs/authentication#service-accounts) in Google Cloud.
