Cloud SQL for PostgreSQL로 데이터베이스 액세스
Teleport can provide secure access to PostgreSQL on Google Cloud SQL via the Teleport Database Service. In this guide, you will:
Teleport can provide secure access to PostgreSQL on Google Cloud SQL via the Teleport Database Service. This allows for fine-grained access control through Teleport's RBAC.
In this guide, you will:
- Configure your PostgreSQL on Google Cloud SQL database 서비스 계정으로.
- Add the database to your Teleport cluster.
- Connect to the database via Teleport.
작동 방식#
The Teleport Database Service uses IAM authentication to communicate with PostgreSQL. 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.


사전 조건#
-
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 `tctl` and `tsh` clients
-
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 with the web address of your Teleport Proxy Service:$ TELEPORT_DOMAIN= $ TELEPORT_VERSION="$(curl -s https://$TELEPORT_DOMAIN/v1/webapi/find | jq -r '.server_version')" -
Follow the instructions for your platform to install
tctlandtshclients:
-
- Google Cloud 계정
- 명령줄 클라이언트
psql이 설치되어 시스템PATH환경 변수에 추가되어 있어야 합니다. - Teleport Database Service를 실행할 호스트(예: Compute Engine 인스턴스)
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 to the domain name of the Teleport Proxy Service in your cluster and to your Teleport username:
$ tsh login --proxy= --user=
$ tctl status
# Cluster (=teleport.url=)
# Version (=teleport.version=)
# CA pin (=presets.ca_pin=)
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.
1/9단계. 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 page and create a service account:

(선택 사항) 권한 부여#
The Teleport Database Service needs permissions to automatically download your Cloud SQL instance's root CA certificate and to general 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.
2/9단계. 데이터베이스 사용자용 서비스 계정 생성#
Teleport는 Cloud SQL 데이터베이스에 연결하기 위해 서비스 계정을 사용합니다.
Create a service account#
Go to the IAM & Admin Service Accounts page and create a new service account named "cloudsql-user":

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:

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:

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

3/9단계. Cloud SQL 데이터베이스 구성#
Teleport는 Cloud SQL PostgreSQL 인스턴스와 함께 IAM 데이터베이스 인증을 사용합니다.
If you're creating
a new PostgreSQL instance, make sure to add the cloudsql.iam_authentication
database flag under "Customize your instance / Flags" section:

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:

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.
데이터베이스 사용자 생성#
이제 Cloud SQL 인스턴스의 Users 페이지로 돌아가서 새 사용자 계정을 추가하세요. 사이드바에서 "Cloud IAM" 인증 유형을 선택하고 두 번째 단계에서 생성한 "cloudsql-user" 서비스 계정을 추가합니다:

"추가"를 누르면 Users 테이블이 다음과 유사하게 표시됩니다:

자세한 내용은 Google Cloud 문서의 IAM 사용자 생성 및 관리를 참조하세요.
4/9단계. 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 to your Teleport cluster hostname and port, but not the scheme (https://).
-
Run your cluster's install script:
$ curl "https:///scripts/install.sh" | sudo bash
5/9단계. Teleport Database Service 구성#
조인 토큰 생성#
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
(=presets.tokens.first=)
(선택 사항) Cloud SQL CA 인증서 다운로드#
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:

Teleport 설정 생성#
This command will generate a Teleport Database Service configuration file and
save it to /etc/teleport.yaml.
6/9단계. GCP 자격 증명 구성#
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. For non-GCE deployments of Teleport, we recommend using workload identity.
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
7/9단계. 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.
You can check the status of the Teleport Database Service with systemctl status teleport
and view its logs with journalctl -fu teleport.
8/9단계. Teleport 사용자 생성#
| 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. |
For more detailed information about database access controls and how to restrict access see RBAC documentation.
9/9단계. 연결#
Database Service가 클러스터에 참여하면 로그인하여 사용 가능한 데이터베이스를 확인합니다:
$ tsh login --proxy=teleport.example.com --user=alice
$ tsh db ls
# Name Description Labels
# -------- ------------------------ --------
# cloudsql GCP Cloud SQL PostgreSQL env=dev
$ tsh login --proxy=mytenant.teleport.sh --user=alice
$ tsh db ls
# Name Description Labels
# -------- ------------------------ --------
# cloudsql GCP Cloud SQL PostgreSQL env=dev
Teleport 역할이 액세스 권한을 가진 데이터베이스만 볼 수 있습니다. 자세한 내용은 RBAC 가이드를 참조하세요.
데이터베이스에 연결할 때 IAM 데이터베이스 사용자로 추가한 데이터베이스 서비스 계정 이름에서 ".gserviceaccount.com" 접미사를 제외한 이름을 사용하세요. 데이터베이스 사용자 이름은 Cloud SQL 인스턴스의 Users 페이지에서 확인할 수 있습니다. "cloudsql" 예제 데이터베이스의 자격 증명을 가져와 연결하려면 에 Google Cloud 프로젝트 ID를 지정합니다:
$ tsh db connect --db-user=cloudsql-user@.iam --db-name=postgres cloudsql
데이터베이스에서 로그아웃하고 자격 증명을 제거하려면:
# 특정 데이터베이스 인스턴스의 자격 증명 제거:
$ tsh db logout cloudsql
# 또는 모든 데이터베이스의 자격 증명 제거:
$ tsh db logout
문제 해결#
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 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 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.
다음 단계#
-
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.
- Google Cloud에서 서비스 계정으로 인증하기에 대해 자세히 알아보세요.
