InfoGrab Docs

AlloyDB를 통한 데이터베이스 액세스

요약

Teleport can provide secure access to AlloyDB via the Teleport Database Service. In this guide, you will: The Teleport Database Service uses IAM authentication to communicate 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:

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

작동 방식#

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.

AlloyDB 액세스를 위한 Teleport 아키텍처

사전 요구 사항#

  • 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 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 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')"
      
    2. Follow the instructions for your platform to install tctl and tsh clients:

  • AlloyDB 클러스터와 인스턴스가 배포된 Google Cloud 계정. 인스턴스가 IAM 데이터베이스 인증을 사용하도록 구성되어 있는지 확인하세요.
  • 명령줄 클라이언트 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/5단계: GCP IAM 구성#

IAM 설정: 데이터베이스 사용자 및 데이터베이스 서비스를 위한 역할#

Teleport가 AlloyDB 인스턴스에 액세스할 수 있도록 두 개의 서비스 계정을 생성해야 합니다:

  • teleport-db-service: AlloyDB 메타데이터에 액세스하기 위한 Teleport Database Service용.
  • alloydb-user: 데이터베이스에 인증하기 위한 최종 사용자용.

Teleport Database Service를 위한 서비스 계정 생성#

GCP 서비스 계정은 승인된 Teleport 사용자를 대신하여 행동할 때 다른 GCP 서비스 계정의 임시 액세스 토큰을 생성하는 Teleport Database Service에 의해 사용됩니다.

서비스 계정 페이지로 이동하여 서비스 계정을 생성합니다:

시스템 서비스 계정 생성

Teleport Database Service는 데이터베이스 연결 정보를 가져오고 클라이언트 인증서를 생성하기 위해 Google Cloud API를 호출하는 권한이 필요합니다.

teleport-db-service 서비스 계정에 미리 정의된 roles/alloydb.client (Cloud AlloyDB 클라이언트) 역할을 할당합니다. 이 역할은 필요한 권한을 부여합니다.

사용자 서비스 계정에 권한 부여

데이터베이스 사용자를 위한 서비스 계정 생성#

Note

데이터베이스 액세스를 위한 표준 GCP 서비스 계정이 이미 있는 경우 새 계정을 생성하는 대신 해당 계정을 사용할 수 있습니다. 아래에 나열된 필수 권한이 있는지 확인하세요.

Teleport는 서비스 계정을 사용하여 AlloyDB 데이터베이스에 연결합니다.

IAM & 관리자 서비스 계정 페이지로 이동하여 alloydb-user라는 새 서비스 계정을 생성합니다:

사용자 서비스 계정 생성

"만들기 및 계속"을 클릭합니다.

alloydb-user 서비스 계정에 다음 미리 정의된 역할을 할당합니다:

사용자 서비스 계정에 권한 부여

서비스 계정에 액세스 권한 부여#

Teleport Database Service는 이 서비스 계정을 가장(impersonate)할 수 있어야 합니다. alloydb-user 서비스 계정 개요 페이지로 이동하여 "액세스가 있는 주체" 탭을 선택합니다:

액세스가 있는 주체 탭 선택

"액세스 권한 부여"를 클릭하고 teleport-db-service 주체 ID를 추가합니다. "서비스 계정 토큰 생성자" 역할을 선택하고 변경 사항을 저장합니다:

Database Service에 서비스 계정 토큰 생성자 권한 부여

2/5단계: 데이터베이스 구성#

IAM 인증 활성화

Teleport는 AlloyDB 인스턴스에 IAM 데이터베이스 인증을 사용합니다.

인스턴스가 IAM 인증을 사용하도록 구성되어 있는지 확인합니다. 인스턴스 설정으로 이동하여 고급 구성 옵션 섹션에서 alloydb.iam_authentication 플래그가 있는지 확인합니다.

IAM 인증 활성화

데이터베이스 사용자 생성#

Note

AlloyDB 인스턴스에 지정된 서비스 계정에 대해 이미 IAM 사용자가 구성되어 있다면 이 단계를 건너뛸 수 있습니다.

AlloyDB 인스턴스의 사용자 페이지로 이동하여 새 사용자 계정을 추가합니다. 사이드바에서 "Cloud IAM" 인증 유형을 선택하고 이전에 생성한 alloydb-user 서비스 계정을 추가합니다.

AlloyDB 사용자 계정 추가

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

AlloyDB 사용자 계정 테이블

3/5단계: Database Service 호스트 생성#

Note

Teleport Database Service를 실행하는 호스트가 이미 있는 경우 이 단계를 건너뛸 수 있습니다. teleport-db-service 서비스 계정의 자격 증명으로 호스트가 구성되어 있는지 확인하세요(GCE의 경우 서비스 계정 연결 또는 워크로드 ID를 통해).

Teleport Database Service를 실행할 Google Compute Engine(GCE) 인스턴스를 생성합니다.

인스턴스를 생성할 때 "보안" 섹션에서 이전에 생성한 teleport-db-service 서비스 계정을 연결합니다. 이를 통해 Teleport Database Service가 Google Cloud API에 인증할 수 있습니다.

기존 GCE 인스턴스에 서비스 계정 연결

기존 GCE 인스턴스가 있는 경우 Google Cloud Console을 통해 서비스 계정을 연결할 수 있습니다.

  1. VM 인스턴스 페이지로 이동하여 인스턴스를 엽니다.
  2. 인스턴스를 중지합니다. 완전히 중지될 때까지 기다립니다.
  3. 인스턴스 세부 정보를 편집합니다.
  4. ID 및 API 액세스 섹션에서 서비스 계정 드롭다운을 찾습니다.
  5. teleport-db-service 서비스 계정을 선택합니다.
  6. 변경 사항을 저장하고 인스턴스를 다시 시작합니다.

기존 GCE 인스턴스가 있는 경우 gcloud 명령줄 도구를 사용하여 서비스 계정을 연결할 수 있습니다.

변수를 설정합니다:

  • 인스턴스 이름
  • 인스턴스 영역
  • GCP 프로젝트 ID

먼저 인스턴스를 중지합니다:

$ gcloud compute instances stop  --zone=

그런 다음 서비스 계정을 설정합니다:

$ gcloud compute instances set-service-account                  \
    --service-account=teleport-db-service@.iam.gserviceaccount.com \
    --zone=

인스턴스를 다시 시작합니다:

$ gcloud compute instances start  --zone=

인스턴스가 지정된 서비스 계정으로 실행되고 있는지 확인합니다:

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

다른 호스트에서 Teleport Database Service를 실행하는 경우 서비스에 자격 증명을 제공해야 합니다. 워크로드 ID 사용을 권장합니다.

서비스 계정 키 사용(비보안)

또는 해당 서비스 계정의 키 탭으로 이동하여 새 키를 생성합니다.

JSON 형식을 선택해야 합니다.

파일을 저장합니다. 이전에 다운로드한 JSON 자격 증명 파일을 가리키도록 GOOGLE_APPLICATION_CREDENTIALS 환경 변수를 설정합니다. 예를 들어 systemd를 사용하여 teleport를 시작하는 경우 서비스의 EnvironmentFile을 편집하여 환경 변수를 포함해야 합니다:

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

서비스 계정 키는 보안 위험이 될 수 있습니다 - 이 가이드에서는 간단함을 위해 키 사용을 설명합니다. 프로덕션 환경에서 서비스 계정 키를 사용하는 것은 권장하지 않습니다. 서비스 계정 인증 방법에 대한 자세한 내용은 Google Cloud 문서의 인증을 참고하세요.

4/5단계: Teleport 구성#

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 to your Teleport cluster hostname and port, but not the scheme (https://).

  2. Run your cluster's install script:

    $ curl "https:///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
(=presets.tokens.first=)

Database Service 구성 및 시작#

아래 명령에서 를 Teleport Proxy Service 또는 Enterprise Cloud 사이트의 호스트 및 포트로 교체하고, 를 AlloyDB 연결 URI로 교체합니다.

연결 URI의 형식은 projects/PROJECT/locations/REGION/clusters/CLUSTER/instances/INSTANCE입니다. Google Cloud 콘솔의 AlloyDB 인스턴스 세부 정보 페이지에서 복사할 수 있습니다.

AlloyDB 연결 URI

다음과 같이 명령을 실행합니다. 지정된 URI에 필수 alloydb:// 접두사를 포함해야 합니다.

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

이 명령은 Teleport Database Service 구성 파일을 생성하여 /etc/teleport.yaml에 저장합니다.

Choose how Teleport connects to AlloyDB

기본적으로 Teleport는 private AlloyDB 엔드포인트를 사용합니다. 이를 public 또는 PSC 엔드포인트로 변경하려면 endpoint_type 필드를 업데이트합니다:

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
동적 리소스

teleport.yaml에서 데이터베이스를 구성하는 대신 동적 데이터베이스 리소스를 생성할 수 있습니다. 이를 통해 Database Service를 재시작하지 않고 데이터베이스를 추가하거나 업데이트할 수 있습니다.

다음 내용으로 alloydb.yaml이라는 파일을 생성합니다:

kind: db
version: v3
metadata:
  name: alloydb-dynamic
  labels:
    env: dev
spec:
  protocol: "postgres"
  uri: "alloydb://


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

5/5단계: 데이터베이스에 연결#

데이터베이스에 대한 액세스 권한 부여#

Note

다음 명령은 새 Teleport 사용자와 역할을 생성합니다. env: dev 레이블이 있는 리소스에 대한 액세스 권한을 부여하는 기존 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.

연결#

Database Service가 클러스터에 연결된 후 사용 가능한 데이터베이스를 보려면 로그인합니다:

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

Teleport 역할이 액세스할 수 있는 데이터베이스만 볼 수 있습니다. 자세한 내용은 RBAC 가이드를 참고하세요.

데이터베이스에 연결할 때 IAM 데이터베이스 사용자로 추가한 데이터베이스 서비스 계정의 이름을 사용하고, .gserviceaccount.com 접미사를 뺍니다. 데이터베이스 사용자 이름은 AlloyDB 인스턴스의 사용자 페이지에 표시됩니다.

아래 명령에서 를 Google Cloud 프로젝트 ID로 교체합니다. alloydb 예시 데이터베이스의 자격 증명을 검색하고 연결합니다:

$ tsh db connect --db-user=alloydb-user@.iam --db-name=postgres alloydb
Tip

버전 17.1부터 웹 UI를 통해 PostgreSQL 데이터베이스에 액세스할 수 있습니다.

데이터베이스에서 로그아웃하고 자격 증명을 제거하려면:

# 특정 데이터베이스 인스턴스의 자격 증명을 제거합니다:
$ tsh db logout alloydb
# 또는 모든 데이터베이스의 자격 증명을 제거합니다:
$ tsh db logout

선택 사항: 최소 권한 액세스#

가능한 경우 필요한 권한만 부여하는 사용자 지정 IAM 역할을 정의하여 최소 권한을 적용합니다.

Teleport Database Service를 위한 사용자 지정 역할#

teleport-db-service 서비스 계정으로 실행되는 Teleport Database Service는 AlloyDB 인스턴스에 액세스하기 위한 권한이 필요합니다.

다음 권한으로 사용자 지정 역할을 생성합니다:

# 클라이언트 인증서 생성에 사용됨
alloydb.clusters.generateClientCertificate
# 연결 정보 가져오기에 사용됨
alloydb.instances.connect

alloydb-user 서비스 계정을 가장하기 위해 기본 제공 "서비스 계정 토큰 생성자" IAM 역할은 필요 이상으로 광범위합니다. 해당 서비스 계정에 대한 권한을 제한하려면 다음만 포함하는 사용자 지정 역할을 생성합니다:

iam.serviceAccounts.getAccessToken

데이터베이스 사용자를 위한 사용자 지정 역할#

데이터베이스 액세스에 사용되는 alloydb-user 서비스 계정은 인스턴스에 연결하고 데이터베이스 사용자로 인증하기 위한 권한이 필요합니다. 다음을 포함하는 사용자 지정 역할을 생성합니다:

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

문제 해결#

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.

다음 단계#

AlloyDB를 통한 데이터베이스 액세스

원문 보기
요약

Teleport can provide secure access to AlloyDB via the Teleport Database Service. In this guide, you will: The Teleport Database Service uses IAM authentication to communicate 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:

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

작동 방식#

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.

AlloyDB 액세스를 위한 Teleport 아키텍처

사전 요구 사항#

  • 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 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 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')"
      
    2. Follow the instructions for your platform to install tctl and tsh clients:

  • AlloyDB 클러스터와 인스턴스가 배포된 Google Cloud 계정. 인스턴스가 IAM 데이터베이스 인증을 사용하도록 구성되어 있는지 확인하세요.
  • 명령줄 클라이언트 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/5단계: GCP IAM 구성#

IAM 설정: 데이터베이스 사용자 및 데이터베이스 서비스를 위한 역할#

Teleport가 AlloyDB 인스턴스에 액세스할 수 있도록 두 개의 서비스 계정을 생성해야 합니다:

  • teleport-db-service: AlloyDB 메타데이터에 액세스하기 위한 Teleport Database Service용.
  • alloydb-user: 데이터베이스에 인증하기 위한 최종 사용자용.

Teleport Database Service를 위한 서비스 계정 생성#

GCP 서비스 계정은 승인된 Teleport 사용자를 대신하여 행동할 때 다른 GCP 서비스 계정의 임시 액세스 토큰을 생성하는 Teleport Database Service에 의해 사용됩니다.

서비스 계정 페이지로 이동하여 서비스 계정을 생성합니다:

시스템 서비스 계정 생성

Teleport Database Service는 데이터베이스 연결 정보를 가져오고 클라이언트 인증서를 생성하기 위해 Google Cloud API를 호출하는 권한이 필요합니다.

teleport-db-service 서비스 계정에 미리 정의된 roles/alloydb.client (Cloud AlloyDB 클라이언트) 역할을 할당합니다. 이 역할은 필요한 권한을 부여합니다.

사용자 서비스 계정에 권한 부여

데이터베이스 사용자를 위한 서비스 계정 생성#

Note

데이터베이스 액세스를 위한 표준 GCP 서비스 계정이 이미 있는 경우 새 계정을 생성하는 대신 해당 계정을 사용할 수 있습니다. 아래에 나열된 필수 권한이 있는지 확인하세요.

Teleport는 서비스 계정을 사용하여 AlloyDB 데이터베이스에 연결합니다.

IAM & 관리자 서비스 계정 페이지로 이동하여 alloydb-user라는 새 서비스 계정을 생성합니다:

사용자 서비스 계정 생성

"만들기 및 계속"을 클릭합니다.

alloydb-user 서비스 계정에 다음 미리 정의된 역할을 할당합니다:

사용자 서비스 계정에 권한 부여

서비스 계정에 액세스 권한 부여#

Teleport Database Service는 이 서비스 계정을 가장(impersonate)할 수 있어야 합니다. alloydb-user 서비스 계정 개요 페이지로 이동하여 "액세스가 있는 주체" 탭을 선택합니다:

액세스가 있는 주체 탭 선택

"액세스 권한 부여"를 클릭하고 teleport-db-service 주체 ID를 추가합니다. "서비스 계정 토큰 생성자" 역할을 선택하고 변경 사항을 저장합니다:

Database Service에 서비스 계정 토큰 생성자 권한 부여

2/5단계: 데이터베이스 구성#

IAM 인증 활성화

Teleport는 AlloyDB 인스턴스에 IAM 데이터베이스 인증을 사용합니다.

인스턴스가 IAM 인증을 사용하도록 구성되어 있는지 확인합니다. 인스턴스 설정으로 이동하여 고급 구성 옵션 섹션에서 alloydb.iam_authentication 플래그가 있는지 확인합니다.

IAM 인증 활성화

데이터베이스 사용자 생성#

Note

AlloyDB 인스턴스에 지정된 서비스 계정에 대해 이미 IAM 사용자가 구성되어 있다면 이 단계를 건너뛸 수 있습니다.

AlloyDB 인스턴스의 사용자 페이지로 이동하여 새 사용자 계정을 추가합니다. 사이드바에서 "Cloud IAM" 인증 유형을 선택하고 이전에 생성한 alloydb-user 서비스 계정을 추가합니다.

AlloyDB 사용자 계정 추가

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

AlloyDB 사용자 계정 테이블

3/5단계: Database Service 호스트 생성#

Note

Teleport Database Service를 실행하는 호스트가 이미 있는 경우 이 단계를 건너뛸 수 있습니다. teleport-db-service 서비스 계정의 자격 증명으로 호스트가 구성되어 있는지 확인하세요(GCE의 경우 서비스 계정 연결 또는 워크로드 ID를 통해).

Teleport Database Service를 실행할 Google Compute Engine(GCE) 인스턴스를 생성합니다.

인스턴스를 생성할 때 "보안" 섹션에서 이전에 생성한 teleport-db-service 서비스 계정을 연결합니다. 이를 통해 Teleport Database Service가 Google Cloud API에 인증할 수 있습니다.

기존 GCE 인스턴스에 서비스 계정 연결

기존 GCE 인스턴스가 있는 경우 Google Cloud Console을 통해 서비스 계정을 연결할 수 있습니다.

  1. VM 인스턴스 페이지로 이동하여 인스턴스를 엽니다.
  2. 인스턴스를 중지합니다. 완전히 중지될 때까지 기다립니다.
  3. 인스턴스 세부 정보를 편집합니다.
  4. ID 및 API 액세스 섹션에서 서비스 계정 드롭다운을 찾습니다.
  5. teleport-db-service 서비스 계정을 선택합니다.
  6. 변경 사항을 저장하고 인스턴스를 다시 시작합니다.

기존 GCE 인스턴스가 있는 경우 gcloud 명령줄 도구를 사용하여 서비스 계정을 연결할 수 있습니다.

변수를 설정합니다:

  • 인스턴스 이름
  • 인스턴스 영역
  • GCP 프로젝트 ID

먼저 인스턴스를 중지합니다:

$ gcloud compute instances stop  --zone=

그런 다음 서비스 계정을 설정합니다:

$ gcloud compute instances set-service-account                  \
    --service-account=teleport-db-service@.iam.gserviceaccount.com \
    --zone=

인스턴스를 다시 시작합니다:

$ gcloud compute instances start  --zone=

인스턴스가 지정된 서비스 계정으로 실행되고 있는지 확인합니다:

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

다른 호스트에서 Teleport Database Service를 실행하는 경우 서비스에 자격 증명을 제공해야 합니다. 워크로드 ID 사용을 권장합니다.

서비스 계정 키 사용(비보안)

또는 해당 서비스 계정의 키 탭으로 이동하여 새 키를 생성합니다.

JSON 형식을 선택해야 합니다.

파일을 저장합니다. 이전에 다운로드한 JSON 자격 증명 파일을 가리키도록 GOOGLE_APPLICATION_CREDENTIALS 환경 변수를 설정합니다. 예를 들어 systemd를 사용하여 teleport를 시작하는 경우 서비스의 EnvironmentFile을 편집하여 환경 변수를 포함해야 합니다:

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

서비스 계정 키는 보안 위험이 될 수 있습니다 - 이 가이드에서는 간단함을 위해 키 사용을 설명합니다. 프로덕션 환경에서 서비스 계정 키를 사용하는 것은 권장하지 않습니다. 서비스 계정 인증 방법에 대한 자세한 내용은 Google Cloud 문서의 인증을 참고하세요.

4/5단계: Teleport 구성#

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 to your Teleport cluster hostname and port, but not the scheme (https://).

  2. Run your cluster's install script:

    $ curl "https:///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
(=presets.tokens.first=)

Database Service 구성 및 시작#

아래 명령에서 를 Teleport Proxy Service 또는 Enterprise Cloud 사이트의 호스트 및 포트로 교체하고, 를 AlloyDB 연결 URI로 교체합니다.

연결 URI의 형식은 projects/PROJECT/locations/REGION/clusters/CLUSTER/instances/INSTANCE입니다. Google Cloud 콘솔의 AlloyDB 인스턴스 세부 정보 페이지에서 복사할 수 있습니다.

AlloyDB 연결 URI

다음과 같이 명령을 실행합니다. 지정된 URI에 필수 alloydb:// 접두사를 포함해야 합니다.

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

이 명령은 Teleport Database Service 구성 파일을 생성하여 /etc/teleport.yaml에 저장합니다.

Choose how Teleport connects to AlloyDB

기본적으로 Teleport는 private AlloyDB 엔드포인트를 사용합니다. 이를 public 또는 PSC 엔드포인트로 변경하려면 endpoint_type 필드를 업데이트합니다:

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
동적 리소스

teleport.yaml에서 데이터베이스를 구성하는 대신 동적 데이터베이스 리소스를 생성할 수 있습니다. 이를 통해 Database Service를 재시작하지 않고 데이터베이스를 추가하거나 업데이트할 수 있습니다.

다음 내용으로 alloydb.yaml이라는 파일을 생성합니다:

kind: db
version: v3
metadata:
  name: alloydb-dynamic
  labels:
    env: dev
spec:
  protocol: "postgres"
  uri: "alloydb://


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

5/5단계: 데이터베이스에 연결#

데이터베이스에 대한 액세스 권한 부여#

Note

다음 명령은 새 Teleport 사용자와 역할을 생성합니다. env: dev 레이블이 있는 리소스에 대한 액세스 권한을 부여하는 기존 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.

연결#

Database Service가 클러스터에 연결된 후 사용 가능한 데이터베이스를 보려면 로그인합니다:

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

Teleport 역할이 액세스할 수 있는 데이터베이스만 볼 수 있습니다. 자세한 내용은 RBAC 가이드를 참고하세요.

데이터베이스에 연결할 때 IAM 데이터베이스 사용자로 추가한 데이터베이스 서비스 계정의 이름을 사용하고, .gserviceaccount.com 접미사를 뺍니다. 데이터베이스 사용자 이름은 AlloyDB 인스턴스의 사용자 페이지에 표시됩니다.

아래 명령에서 를 Google Cloud 프로젝트 ID로 교체합니다. alloydb 예시 데이터베이스의 자격 증명을 검색하고 연결합니다:

$ tsh db connect --db-user=alloydb-user@.iam --db-name=postgres alloydb
Tip

버전 17.1부터 웹 UI를 통해 PostgreSQL 데이터베이스에 액세스할 수 있습니다.

데이터베이스에서 로그아웃하고 자격 증명을 제거하려면:

# 특정 데이터베이스 인스턴스의 자격 증명을 제거합니다:
$ tsh db logout alloydb
# 또는 모든 데이터베이스의 자격 증명을 제거합니다:
$ tsh db logout

선택 사항: 최소 권한 액세스#

가능한 경우 필요한 권한만 부여하는 사용자 지정 IAM 역할을 정의하여 최소 권한을 적용합니다.

Teleport Database Service를 위한 사용자 지정 역할#

teleport-db-service 서비스 계정으로 실행되는 Teleport Database Service는 AlloyDB 인스턴스에 액세스하기 위한 권한이 필요합니다.

다음 권한으로 사용자 지정 역할을 생성합니다:

# 클라이언트 인증서 생성에 사용됨
alloydb.clusters.generateClientCertificate
# 연결 정보 가져오기에 사용됨
alloydb.instances.connect

alloydb-user 서비스 계정을 가장하기 위해 기본 제공 "서비스 계정 토큰 생성자" IAM 역할은 필요 이상으로 광범위합니다. 해당 서비스 계정에 대한 권한을 제한하려면 다음만 포함하는 사용자 지정 역할을 생성합니다:

iam.serviceAccounts.getAccessToken

데이터베이스 사용자를 위한 사용자 지정 역할#

데이터베이스 액세스에 사용되는 alloydb-user 서비스 계정은 인스턴스에 연결하고 데이터베이스 사용자로 인증하기 위한 권한이 필요합니다. 다음을 포함하는 사용자 지정 역할을 생성합니다:

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

문제 해결#

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.

다음 단계#