InfoGrab Docs

셀프 호스팅 CockroachDB를 사용한 데이터베이스 접근

요약

Teleport can provide secure access to CockroachDB via the Teleport Database Service. The Teleport Database Service proxies traffic from database clients to self-hosted databases in your infrastructure.

Teleport can provide secure access to CockroachDB via the Teleport Database Service. This allows for fine-grained access control through the Teleport RBAC system.

The Teleport Database Service proxies traffic from database clients to self-hosted databases in your infrastructure. Teleport maintains a certificate authority (CA) for database clients. You configure your database to trust the Teleport database client CA, and the Teleport Database Service presents certificates signed by this CA when proxying user traffic. With this setup, there is no need to store long-lived credentials for self-hosted databases.

Meanwhile, the Teleport Database Service verifies self-hosted databases by checking their TLS certificates against either the Teleport database CA or a custom CA used with the database.

In this guide, you will:

  1. Configure your CockroachDB database for Teleport access.
  2. Add the database to your Teleport cluster.
  3. Connect to the database via Teleport.

작동 방식#

The Teleport Database Service authenticates to your self-hosted CockroachDB database using mutual TLS. CockroachDB trusts the Teleport certificate authority for database clients, and presents a certificate signed by either the Teleport database CA or a custom CA. When a user initiates a database session, the Teleport Database Service presents a certificate signed by Teleport. The authenticated connection then proxies client traffic from the user.

셀프 호스팅 Teleport 클러스터로 CockroachDB 인스턴스 등록

클라우드 호스팅 Teleport 클러스터로 CockroachDB 인스턴스 등록

사전 조건#

  • 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:

  • CockroachDB 클러스터.

  • Teleport 데이터베이스 서비스를 실행할 호스트(예: Amazon EC2 인스턴스).

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.

  • CockroachDB 클러스터의 노드에 대해 CockroachDB 인증서를 발급하는 인증 기관.
Why do I need my own CA? Distributed databases like CockroachDB use mTLS for node-to-node communication. Teleport requires that you have your own CA to issue certificates for node-to-node mTLS communication.

Teleport uses a split-CA architecture for database access. The Teleport db CA issues server certificates and the db_client CA issues client certificates.

Databases are configured to trust the Teleport db_client CA for client authentication, but not the db CA. Additionally, Teleport only issues ephemeral db_client CA certificates.

When a CockroachDB node connects to another CockroachDB node, it must present a certificate that the other node trusts for client authentication. Since Teleport does not issue long-lived db_client certificates, the node needs to have a long-lived certificate issued by another CA that its peer node trusts.

The split db and db_client CA architecture was introduced as a security fix in Teleport versions (= db_client_ca.released_version.v14 =) and (= db_client_ca.released_version.v15 =).

See Database CA Migrations for more information.

1/4단계. Teleport 데이터베이스 서비스 설정#

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=)

Teleport 데이터베이스 서비스를 실행할 위치에 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 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
    

On the host where you will run the Teleport Database Service, start Teleport with the appropriate configuration.

Note that a single Teleport process can run multiple different services, for example multiple Database Service agents as well as the SSH Service or Application Service. The step below will overwrite an existing configuration file, so if you're running multiple services add --output=stdout to print the config in your terminal, and manually adjust /etc/teleport.yaml.

Generate a configuration file at /etc/teleport.yaml for the Database Service:

(!docs/pages/includes/start-teleport.mdx service="the Teleport Database Service"!)

Teleport는 Kubernetes 클러스터에 Teleport 데이터베이스 서비스를 설치하기 위한 Helm 차트를 제공합니다.

Configure Helm to fetch Teleport charts from the Teleport Helm repository:

$ helm repo add teleport (=teleport.helm_repo_url=)

Refresh the local Helm cache by fetching the latest charts:

$ helm repo update

Make sure that the Teleport Agent pod is running. You should see one teleport-kube-agent pod with a single ready container:

$ kubectl -n teleport-agent get pods
NAME                    READY   STATUS    RESTARTS   AGE
teleport-kube-agent-0   1/1     Running   0          32s

(!docs/pages/includes/database-access/multiple-instances-tip.mdx !)

2/4단계. 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.

3/4단계. CockroachDB 구성#

CockroachDB 사용자 생성#

Teleport는 CockroachDB와 상호 TLS 인증을 사용합니다. 클라이언트 인증서 인증은 모든 CockroachDB 사용자에게 사용 가능합니다. 아직 없는 경우 Cockroach 클러스터에 연결하여 생성합니다:

CREATE USER alice WITH PASSWORD NULL;

WITH PASSWORD NULL 절은 사용자가 패스워드 인증을 사용하지 못하게 하고 클라이언트 인증서 인증을 의무화합니다.

데이터베이스 클러스터 내에서 사용자에게 적절한 권한을 할당해야 합니다. 자세한 정보는 CockroachDB 문서의 사용자 생성을 참조하세요.

상호 TLS 설정#

상호 TLS 인증을 설정하려면 다음을 확인해야 합니다:

  • Teleport가 CockroachDB 노드에서 제시하는 인증서를 신뢰합니다.
  • CockroachDB 노드가 CockroachDB CA와 Teleport 클러스터의 db_client CA 모두에서 서명된 클라이언트 인증서를 신뢰합니다.

CockroachDB 노드는 Teleport 사용자가 클라이언트로서 CockroachDB 클러스터에 인증할 수 있도록 Teleport db_client CA를 신뢰해야 합니다.

CockroachDB CA는 노드가 CockroachDB 클러스터 내의 다른 노드에 클라이언트로서 인증할 수 있도록 각 CockroachDB 노드에서 신뢰되어야 합니다. 이는 CockroachDB가 노드 간 통신에 mTLS를 사용하기 때문입니다.

이 구성에서는 CockroachDB CA가 각 CockroachDB 노드의 서버 인증서 node.crt를 발급하는 데 사용됩니다.

이 구성은 설정이 더 간단합니다. 기존 CockroachDB 클러스터는 이미 각 노드에 대해 node.crt가 발급되어 있으므로, CockroachDB 노드가 Teleport db_client CA를 신뢰하도록 구성하기만 하면 됩니다. 또 다른 이점은 CockroachDB 노드가 Teleport의 db CA에서 서명한 새 인증서를 제공하는 대신 동일한 CockroachDB CA 발급 인증서를 계속 제공하므로, 다른 클라이언트에 새 CA를 신뢰하도록 구성할 필요가 없다는 것입니다.

각 CockroachDB 노드의 인증서 디렉터리에서 CockroachDB CA 인증서를 ca-client.crt에 복사합니다:

$ CERTS_DIR=
$ cp "${CERTS_DIR}/ca.crt" "${CERTS_DIR}/ca-client.crt"

다음으로, 각 CockroachDB 노드에 대해 tctl을 사용하여 Teleport의 db_client CA를 내보내고(또는 한 번 내보내서 각 노드에 복사) ca-client.crt에 인증서를 추가합니다:

$ tctl auth export --type=db-client >> /ca-client.crt

Modify the Teleport Database Service to trust your CockroachDB CA, assigning to the path to your CA certificate:

  databases:
  - name: "example-cockroachdb"
    protocol: "cockroachdb"
    uri: "cockroachdb.example.com:26257"
    static_labels:
      "env": "example"
    tls:
      ca_cert_file: ""

Now the Teleport Database Service will trust certificates presented by your CockroachDB.

이 구성에서는 Teleport의 CA가 서버 인증서 node.crt를 발급하는 데 사용되고, 사용자 지정 CA는 각 CockroachDB 노드의 클라이언트 인증서 client.node.crt를 발급하는 데 사용됩니다.

Teleport uses mutual TLS authentication with self-hosted databases. These databases must be configured with Teleport's certificate authority to be able to verify client certificates. They also need a certificate/key pair that Teleport can verify.

To use issue certificates from your workstation with tctl, your Teleport user must be allowed to impersonate the system role Db.

Include the following allow rule in in your Teleport user's role:

allow:
  impersonate:
    users: ["Db"]
    roles: ["Db"]

tctl을 사용하여 CockroachDB 노드의 시크릿을 생성합니다:

$ tctl auth sign \
    --format=cockroachdb \
    --host=roach.example.com \
    --out= \
    --ttl=2190h

이 명령은 4개의 파일을 생성합니다:

  • Teleport의 db 인증 기관이 포함된 ca.crt
  • Teleport의 db_client 인증 기관이 포함된 ca-client.crt
  • 노드의 인증서와 키가 포함된 node.crt / node.key.
Note

여러 쉼표로 구분된 주소를 지정할 수 있습니다. 예: --host=roach,node-1,192.168.1.1. 단, Teleport가 데이터베이스에 연결하는 데 사용할 호스트명을 포함해야 합니다.

CockroachDB가 파일 이름을 기대하는 방식이므로 이 파일들의 이름을 변경하지 마세요. 자세한 내용은 노드 키와 인증서를 참조하세요.

CockroachDB CA의 인증서를 ca-client.crt 앞에 추가합니다. 이제 CockroachDB CA를 사용하여 노드의 클라이언트 인증서를 발급합니다:

$ cockroach cert create-client node \
  --certs-dir= \
  --ca-key=ca-secrets/ca-client.key
TLS 키 불일치에 대한 오류 메시지가 표시됩니까? `tls: private key does not match public key`와 같은 오류 메시지가 표시되면, 이전에 CockroachDB CA 인증서를 `ca-client.crt` 앞에 추가하지 않았을 가능성이 높습니다.

cockroach cert create-clientca-client.crt의 첫 번째 인증서(--certs-dir에 지정된)가 --ca-key에 의해 서명된 인증서여야 한다고 기대합니다. CockroachDB CA 인증서가 ca-client.crt의 첫 번째 인증서인지 확인하세요.

이제 을 CockroachDB 노드에 복사하고 다른 모든 CockroachDB 노드에 대해 이 단계를 반복합니다.

--certs-dir 플래그를 통해 생성된 시크릿 디렉터리를 전달하여 CockroachDB 노드를 재시작합니다:

$ cockroach start \
    --certs-dir= \
    # 다른 플래그들...

또는 노드가 이미 --certs-dir=으로 시작된 경우, 노드를 재시작하지 않고 cockroach 프로세스에 SIGHUP 신호를 보내 인증서를 다시 로드할 수 있습니다. cockroach 프로세스를 시작한 것과 동일한 사용자로 SIGHUP을 보내야 합니다:

$ pkill -SIGHUP -x cockroach

4/4단계. 연결#

Teleport 클러스터에 로그인합니다. CockroachDB 클러스터가 사용 가능한 데이터베이스 목록에 표시되어야 합니다:

$ tsh login --proxy=teleport.example.com --user=alice
$ tsh db ls
# Name  Description         Labels
# ----- ------------------- -------
# roach Example CockroachDB env=dev
$ tsh login --proxy=mytenant.teleport.sh --user=alice
$ tsh db ls
# Name  Description         Labels
# ----- ------------------- -------
# roach Example CockroachDB env=dev

데이터베이스의 자격 증명을 가져와서 연결하려면:

$ tsh db connect roach

데이터베이스 서버에 연결할 때 기본적으로 사용할 데이터베이스 이름과 사용자를 선택적으로 지정할 수 있습니다:

$ tsh db connect --db-user=alice roach
Note

이 섹션의 내용은 원문 문서를 참조하세요. (proxy-db-tunnel.mdx)

Note

연결하려면 PATHcockroach 또는 psql 커맨드라인 클라이언트가 있어야 합니다.

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

$ tsh db logout roach

문제 해결#

구현되지 않은 클라이언트 인코딩 오류#

psql이 SQL_ASCII 인코딩을 사용하는 경우 CockroachDB 데이터베이스에 연결할 때 unimplemented client encoding: "sqlascii" 오류가 발생할 수 있습니다.

CockroachDB는 UTF8 클라이언트 인코딩만 지원합니다. 인코딩을 강제 적용하려면 tsh db connect를 실행하는 쉘에서 다음 환경 변수를 설정하세요:

export PGCLIENTENCODING='utf-8'

Teleport Connect로 CockroachDB 데이터베이스에 연결하는 경우 쉘 시작 스크립트에 환경 변수를 추가하고 Teleport Connect 앱을 재시작하세요.

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.

다음 단계#

셀프 호스팅 CockroachDB를 사용한 데이터베이스 접근

원문 보기
요약

Teleport can provide secure access to CockroachDB via the Teleport Database Service. The Teleport Database Service proxies traffic from database clients to self-hosted databases in your infrastructure.

Teleport can provide secure access to CockroachDB via the Teleport Database Service. This allows for fine-grained access control through the Teleport RBAC system.

The Teleport Database Service proxies traffic from database clients to self-hosted databases in your infrastructure. Teleport maintains a certificate authority (CA) for database clients. You configure your database to trust the Teleport database client CA, and the Teleport Database Service presents certificates signed by this CA when proxying user traffic. With this setup, there is no need to store long-lived credentials for self-hosted databases.

Meanwhile, the Teleport Database Service verifies self-hosted databases by checking their TLS certificates against either the Teleport database CA or a custom CA used with the database.

In this guide, you will:

  1. Configure your CockroachDB database for Teleport access.
  2. Add the database to your Teleport cluster.
  3. Connect to the database via Teleport.

작동 방식#

The Teleport Database Service authenticates to your self-hosted CockroachDB database using mutual TLS. CockroachDB trusts the Teleport certificate authority for database clients, and presents a certificate signed by either the Teleport database CA or a custom CA. When a user initiates a database session, the Teleport Database Service presents a certificate signed by Teleport. The authenticated connection then proxies client traffic from the user.

셀프 호스팅 Teleport 클러스터로 CockroachDB 인스턴스 등록

클라우드 호스팅 Teleport 클러스터로 CockroachDB 인스턴스 등록

사전 조건#

  • 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:

  • CockroachDB 클러스터.

  • Teleport 데이터베이스 서비스를 실행할 호스트(예: Amazon EC2 인스턴스).

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.

  • CockroachDB 클러스터의 노드에 대해 CockroachDB 인증서를 발급하는 인증 기관.
Why do I need my own CA? Distributed databases like CockroachDB use mTLS for node-to-node communication. Teleport requires that you have your own CA to issue certificates for node-to-node mTLS communication.

Teleport uses a split-CA architecture for database access. The Teleport db CA issues server certificates and the db_client CA issues client certificates.

Databases are configured to trust the Teleport db_client CA for client authentication, but not the db CA. Additionally, Teleport only issues ephemeral db_client CA certificates.

When a CockroachDB node connects to another CockroachDB node, it must present a certificate that the other node trusts for client authentication. Since Teleport does not issue long-lived db_client certificates, the node needs to have a long-lived certificate issued by another CA that its peer node trusts.

The split db and db_client CA architecture was introduced as a security fix in Teleport versions (= db_client_ca.released_version.v14 =) and (= db_client_ca.released_version.v15 =).

See Database CA Migrations for more information.

1/4단계. Teleport 데이터베이스 서비스 설정#

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=)

Teleport 데이터베이스 서비스를 실행할 위치에 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 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
    

On the host where you will run the Teleport Database Service, start Teleport with the appropriate configuration.

Note that a single Teleport process can run multiple different services, for example multiple Database Service agents as well as the SSH Service or Application Service. The step below will overwrite an existing configuration file, so if you're running multiple services add --output=stdout to print the config in your terminal, and manually adjust /etc/teleport.yaml.

Generate a configuration file at /etc/teleport.yaml for the Database Service:

(!docs/pages/includes/start-teleport.mdx service="the Teleport Database Service"!)

Teleport는 Kubernetes 클러스터에 Teleport 데이터베이스 서비스를 설치하기 위한 Helm 차트를 제공합니다.

Configure Helm to fetch Teleport charts from the Teleport Helm repository:

$ helm repo add teleport (=teleport.helm_repo_url=)

Refresh the local Helm cache by fetching the latest charts:

$ helm repo update

Make sure that the Teleport Agent pod is running. You should see one teleport-kube-agent pod with a single ready container:

$ kubectl -n teleport-agent get pods
NAME                    READY   STATUS    RESTARTS   AGE
teleport-kube-agent-0   1/1     Running   0          32s

(!docs/pages/includes/database-access/multiple-instances-tip.mdx !)

2/4단계. 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.

3/4단계. CockroachDB 구성#

CockroachDB 사용자 생성#

Teleport는 CockroachDB와 상호 TLS 인증을 사용합니다. 클라이언트 인증서 인증은 모든 CockroachDB 사용자에게 사용 가능합니다. 아직 없는 경우 Cockroach 클러스터에 연결하여 생성합니다:

CREATE USER alice WITH PASSWORD NULL;

WITH PASSWORD NULL 절은 사용자가 패스워드 인증을 사용하지 못하게 하고 클라이언트 인증서 인증을 의무화합니다.

데이터베이스 클러스터 내에서 사용자에게 적절한 권한을 할당해야 합니다. 자세한 정보는 CockroachDB 문서의 사용자 생성을 참조하세요.

상호 TLS 설정#

상호 TLS 인증을 설정하려면 다음을 확인해야 합니다:

  • Teleport가 CockroachDB 노드에서 제시하는 인증서를 신뢰합니다.
  • CockroachDB 노드가 CockroachDB CA와 Teleport 클러스터의 db_client CA 모두에서 서명된 클라이언트 인증서를 신뢰합니다.

CockroachDB 노드는 Teleport 사용자가 클라이언트로서 CockroachDB 클러스터에 인증할 수 있도록 Teleport db_client CA를 신뢰해야 합니다.

CockroachDB CA는 노드가 CockroachDB 클러스터 내의 다른 노드에 클라이언트로서 인증할 수 있도록 각 CockroachDB 노드에서 신뢰되어야 합니다. 이는 CockroachDB가 노드 간 통신에 mTLS를 사용하기 때문입니다.

이 구성에서는 CockroachDB CA가 각 CockroachDB 노드의 서버 인증서 node.crt를 발급하는 데 사용됩니다.

이 구성은 설정이 더 간단합니다. 기존 CockroachDB 클러스터는 이미 각 노드에 대해 node.crt가 발급되어 있으므로, CockroachDB 노드가 Teleport db_client CA를 신뢰하도록 구성하기만 하면 됩니다. 또 다른 이점은 CockroachDB 노드가 Teleport의 db CA에서 서명한 새 인증서를 제공하는 대신 동일한 CockroachDB CA 발급 인증서를 계속 제공하므로, 다른 클라이언트에 새 CA를 신뢰하도록 구성할 필요가 없다는 것입니다.

각 CockroachDB 노드의 인증서 디렉터리에서 CockroachDB CA 인증서를 ca-client.crt에 복사합니다:

$ CERTS_DIR=
$ cp "${CERTS_DIR}/ca.crt" "${CERTS_DIR}/ca-client.crt"

다음으로, 각 CockroachDB 노드에 대해 tctl을 사용하여 Teleport의 db_client CA를 내보내고(또는 한 번 내보내서 각 노드에 복사) ca-client.crt에 인증서를 추가합니다:

$ tctl auth export --type=db-client >> /ca-client.crt

Modify the Teleport Database Service to trust your CockroachDB CA, assigning to the path to your CA certificate:

  databases:
  - name: "example-cockroachdb"
    protocol: "cockroachdb"
    uri: "cockroachdb.example.com:26257"
    static_labels:
      "env": "example"
    tls:
      ca_cert_file: ""

Now the Teleport Database Service will trust certificates presented by your CockroachDB.

이 구성에서는 Teleport의 CA가 서버 인증서 node.crt를 발급하는 데 사용되고, 사용자 지정 CA는 각 CockroachDB 노드의 클라이언트 인증서 client.node.crt를 발급하는 데 사용됩니다.

Teleport uses mutual TLS authentication with self-hosted databases. These databases must be configured with Teleport's certificate authority to be able to verify client certificates. They also need a certificate/key pair that Teleport can verify.

To use issue certificates from your workstation with tctl, your Teleport user must be allowed to impersonate the system role Db.

Include the following allow rule in in your Teleport user's role:

allow:
  impersonate:
    users: ["Db"]
    roles: ["Db"]

tctl을 사용하여 CockroachDB 노드의 시크릿을 생성합니다:

$ tctl auth sign \
    --format=cockroachdb \
    --host=roach.example.com \
    --out= \
    --ttl=2190h

이 명령은 4개의 파일을 생성합니다:

  • Teleport의 db 인증 기관이 포함된 ca.crt
  • Teleport의 db_client 인증 기관이 포함된 ca-client.crt
  • 노드의 인증서와 키가 포함된 node.crt / node.key.
Note

여러 쉼표로 구분된 주소를 지정할 수 있습니다. 예: --host=roach,node-1,192.168.1.1. 단, Teleport가 데이터베이스에 연결하는 데 사용할 호스트명을 포함해야 합니다.

CockroachDB가 파일 이름을 기대하는 방식이므로 이 파일들의 이름을 변경하지 마세요. 자세한 내용은 노드 키와 인증서를 참조하세요.

CockroachDB CA의 인증서를 ca-client.crt 앞에 추가합니다. 이제 CockroachDB CA를 사용하여 노드의 클라이언트 인증서를 발급합니다:

$ cockroach cert create-client node \
  --certs-dir= \
  --ca-key=ca-secrets/ca-client.key
TLS 키 불일치에 대한 오류 메시지가 표시됩니까? `tls: private key does not match public key`와 같은 오류 메시지가 표시되면, 이전에 CockroachDB CA 인증서를 `ca-client.crt` 앞에 추가하지 않았을 가능성이 높습니다.

cockroach cert create-clientca-client.crt의 첫 번째 인증서(--certs-dir에 지정된)가 --ca-key에 의해 서명된 인증서여야 한다고 기대합니다. CockroachDB CA 인증서가 ca-client.crt의 첫 번째 인증서인지 확인하세요.

이제 을 CockroachDB 노드에 복사하고 다른 모든 CockroachDB 노드에 대해 이 단계를 반복합니다.

--certs-dir 플래그를 통해 생성된 시크릿 디렉터리를 전달하여 CockroachDB 노드를 재시작합니다:

$ cockroach start \
    --certs-dir= \
    # 다른 플래그들...

또는 노드가 이미 --certs-dir=으로 시작된 경우, 노드를 재시작하지 않고 cockroach 프로세스에 SIGHUP 신호를 보내 인증서를 다시 로드할 수 있습니다. cockroach 프로세스를 시작한 것과 동일한 사용자로 SIGHUP을 보내야 합니다:

$ pkill -SIGHUP -x cockroach

4/4단계. 연결#

Teleport 클러스터에 로그인합니다. CockroachDB 클러스터가 사용 가능한 데이터베이스 목록에 표시되어야 합니다:

$ tsh login --proxy=teleport.example.com --user=alice
$ tsh db ls
# Name  Description         Labels
# ----- ------------------- -------
# roach Example CockroachDB env=dev
$ tsh login --proxy=mytenant.teleport.sh --user=alice
$ tsh db ls
# Name  Description         Labels
# ----- ------------------- -------
# roach Example CockroachDB env=dev

데이터베이스의 자격 증명을 가져와서 연결하려면:

$ tsh db connect roach

데이터베이스 서버에 연결할 때 기본적으로 사용할 데이터베이스 이름과 사용자를 선택적으로 지정할 수 있습니다:

$ tsh db connect --db-user=alice roach
Note

이 섹션의 내용은 원문 문서를 참조하세요. (proxy-db-tunnel.mdx)

Note

연결하려면 PATHcockroach 또는 psql 커맨드라인 클라이언트가 있어야 합니다.

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

$ tsh db logout roach

문제 해결#

구현되지 않은 클라이언트 인코딩 오류#

psql이 SQL_ASCII 인코딩을 사용하는 경우 CockroachDB 데이터베이스에 연결할 때 unimplemented client encoding: "sqlascii" 오류가 발생할 수 있습니다.

CockroachDB는 UTF8 클라이언트 인코딩만 지원합니다. 인코딩을 강제 적용하려면 tsh db connect를 실행하는 쉘에서 다음 환경 변수를 설정하세요:

export PGCLIENTENCODING='utf-8'

Teleport Connect로 CockroachDB 데이터베이스에 연결하는 경우 쉘 시작 스크립트에 환경 변수를 추가하고 Teleport Connect 앱을 재시작하세요.

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.

다음 단계#