Amazon RDS 및 Aurora PostgreSQL/MySQL/MariaDB를 이용한 데이터베이스 접근
Teleport can provide secure access to Amazon RDS or Aurora via the Teleport Database Service. In this guide, you will: The Teleport Database Service uses IAM authentication to communicate with RDS.
Teleport can provide secure access to Amazon RDS or Aurora via the Teleport Database Service. This allows for fine-grained access control through Teleport's RBAC.
In this guide, you will:
- Configure your Amazon RDS or Aurora database with IAM authentication.
- Add the database to your Teleport cluster.
- Connect to the database via Teleport.
작동 방식#
The Teleport Database Service uses IAM authentication to communicate with RDS. When a user connects to the database via Teleport, the Teleport Database Service obtains AWS credentials and authenticates to AWS as an IAM principal with permissions to access the database.


다음 제품은 IAM 인증을 지원하지 않아 Teleport와 호환되지 않습니다:
- Aurora Serverless v1.
- RDS MariaDB 버전 10.6 미만.
IAM 인증을 지원하는 Aurora Serverless v2로 Aurora Serverless v1을 업그레이드하는 것을 권장합니다.
This guide shows how to register a single RDS with your Teleport cluster. For a more scalable approach, learn how to set up Database Auto-Discovery to automatically enroll all AWS databases in your infrastructure.
전제 조건#
-
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:
-
- IAM 정책을 생성하고 연결할 권한이 있는 RDS 및 Aurora 데이터베이스가 있는 AWS 계정.
IAM 인증
RDS 및 Aurora 데이터베이스에 암호와 IAM 인증이 활성화되어 있어야 합니다.
대상 RDS 및 Aurora 데이터베이스에 IAM 인증이 활성화되어 있지 않으면 데이터베이스 서비스는 각각의 API를 사용하여 수정함으로써 IAM 인증을 활성화하려고 시도합니다.
- RDS 데이터베이스에 대한 연결을 프록시하는 Teleport 데이터베이스 서비스를 실행할 Linux 호스트 또는 Amazon Elastic Kubernetes 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 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 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.Kubernetes에서 Teleport 데이터베이스 서비스를 실행할 계획이라면 다음이 필요합니다:
-
PATH에
awsCLI가 있어야 합니다. AWS 문서를 따라 설치합니다. -
Kubernetes 클러스터에서 실행 중인 IAM OIDC 제공자. IAM OIDC 제공자를 생성하는 방법은 AWS 문서를 참조하세요.
클러스터에서 IAM OIDC 제공자가 실행 중인지 확인하려면 다음
aws명령을 실행하세요. 을 EKS 클러스터가 실행 중인 리전으로, 을 Kubernetes 클러스터 이름으로 지정합니다:$ aws --region= eks describe-cluster --name --query "cluster.identity.oidc.issuer" --output text클러스터와 연결된 IAM OIDC 제공자가 있으면 이 명령은 해당 ID를 출력합니다.
-
이 가이드에서 JSON 데이터를 처리하는 데 사용하는
jqCLI 도구.
1/6단계. Teleport 사용자 생성#
Flag Description --rolesList of roles to assign to the user. The builtin accessrole allows them to connect to any database server registered with Teleport.--db-usersList of database usernames the user will be allowed to use when connecting to the databases. A wildcard allows any user. --db-namesList 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.
2/6단계. 데이터베이스 서비스 구성 생성#
이 섹션에서는 Teleport 데이터베이스 서비스를 구성합니다. 이를 위해 다음을 수행합니다:
- 서비스가 Teleport 클러스터와 신뢰를 확립할 조인 토큰을 생성합니다.
- 데이터베이스 서비스를 설치하고 실행할 수 있도록 패키지 관리자를 설정합니다.
- 데이터베이스 서비스 구성을 생성합니다.
조인 토큰 생성#
조인 토큰을 생성하여 Teleport 데이터베이스 서비스와 Teleport 클러스터 간에 신뢰를 확립합니다.
워크스테이션에서 다음 명령을 실행하여 조인 토큰을 생성합니다:
$ tctl tokens add --type=db다음 단계는 Teleport 데이터베이스 서비스를 실행할 방법에 따라 다릅니다:
데이터베이스 서비스를 실행할 호스트의
/tmp/token파일에 토큰을 저장합니다.이 가이드의 후반부에서 Teleport 데이터베이스 서비스를 구성할 때 이 조인 토큰을 사용합니다.
Alternative methods
For users with a lot of infrastructure in AWS, or who might create or recreate many instances, consider alternative methods for joining new EC2 instances running 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.
-
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
다음 정보를 제공한 다음 Teleport 데이터베이스 서비스 구성 파일을 생성합니다:
- Teleport 프록시 서비스 또는 클라우드 호스팅 Teleport 엔터프라이즈 사이트의 호스트 및 포트
- 프록시하려는 데이터베이스의 프로토콜(
mysql또는postgres) - 데이터베이스의 엔드포인트 및 포트 - Aurora의 클러스터 엔드포인트 또는 RDS 인스턴스의 인스턴스 엔드포인트(예:
myrds.us-east-1.rds.amazonaws.com:5432)
$ sudo teleport db configure create \ -o file \ --name=rds-example \ --proxy= \ --protocol= \ --uri= \ --labels=env=dev \ --token=/tmp/token명령은 Teleport 데이터베이스 서비스 구성 파일을 생성하고
/etc/teleport.yaml위치에 저장합니다.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 update3/6단계. Teleport를 위한 IAM 정책 생성#
The Teleport Database Service needs AWS IAM permissions to provide access to RDS instances and Aurora clusters.
Teleport를 위한 IAM 역할 생성#
Grant the Database Service access to credentials that it can use to authenticate to AWS.
- If you are running the Database Service on an EC2 instance, you may use the EC2 Instance Metadata Service method
- If you are running the Database Service in Kubernetes, you can use IAM Roles for Service Accounts (IRSA)
- Otherwise, you must use environment variables
Have multiple sources of AWS credentials?
Teleport's AWS client loads credentials from different sources in the following order:
- Environment Variables
- Shared credentials file
- Shared configuration file (Teleport always enables shared configuration)
- EC2 Instance Metadata (credentials only)
While you can provide AWS credentials via a shared credentials file or shared configuration file, you will need to run the Database Service with the
AWS_PROFILEenvironment variable assigned to the name of your profile of choice.If you have a specific use case that the instructions above do not account for, consult the documentation for the AWS SDK for Go for a detailed description of credential loading behavior.
권한 부여#
데이터베이스 서비스 IAM 역할에 다음 AWS IAM 권한을 연결합니다:
{ "Version": "2012-10-17", "Statement": [ { "Sid": "RDSAutoEnableIAMAuth", "Effect": "Allow", "Action": [ "rds:ModifyDBCluster", "rds:ModifyDBInstance" ], "Resource": "*" }, { "Sid": "RDSConnect", "Effect": "Allow", "Action": "rds-db:connect", "Resource": "*" }, { "Sid": "RDSFetchMetadata", "Effect": "Allow", "Action": [ "rds:DescribeDBClusters", "rds:DescribeDBInstances" ], "Resource": "*" } ] }Statement Purpose RDSAutoEnableIAMAuthAutomatically enable IAM auth on RDS instances and Aurora clusters. RDSConnectGenerate an IAM authentication token to connect to a database. RDSFetchMetadataAutomatically import AWS tags as database labels or find missing information such as the database's AWS region. The Teleport Database Service uses
rds:ModifyDBInstanceandrds:ModifyDBClusterto automatically enable IAM authentication on RDS instances and Aurora clusters, respectively. You can omit theRDSAutoEnableIAMAuthpermissions if IAM authentication is already enabled on your databases.(!docs/pages/includes/database-access/reference/rds-action-notes-on-connect.mdx!)
(!docs/pages/includes/database-access/reference/metadata-fetching-permissions-note.mdx sid="RDSFetchMetadata"!)
4/6단계. 데이터베이스 서비스 시작#
환경에서 Teleport 데이터베이스 서비스를 시작합니다:
Configure the 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 Database Service.
You can check the status of the Database Service with
systemctl status teleportand view its logs withjournalctl -fu teleport.다음 명령을 실행하고
Db유형의 토큰을 복사하여 이 가이드에서 이전에 생성한 조인 토큰을 검색합니다:$ tctl tokens ls Token Type Labels Expiry Time (UTC) -------------------------------- ---- ------ ---------------------------- (=presets.tokens.first=) Db 14 Jun 23 21:21 UTC (20m15s)Helm 값 파일
values.yaml을 만듭니다. 을 위에서 검색한 조인 토큰 값으로, 을 Teleport 프록시 서비스의 호스트 및 포트로, 을 RDS 데이터베이스의 호스트 및 포트(예:myrds.us-east-1.rds.amazonaws.com:5432)로 지정합니다. 을 AWS 계정 ID로 지정합니다. Teleport 커뮤니티 에디션을 사용하는 경우enterprise를 false로 설정합니다:authToken:(!docs/pages/includes/database-access/db-access-webui-ad.mdx dbType="MySQL or MariaDB"!)
(!docs/pages/includes/database-access/db-access-webui-ad.mdx dbType="PostgreSQL"!)
데이터베이스에서 로그아웃하고 자격 증명을 제거합니다:
$ tsh db logout rds-example문제 해결#
Certificate error#
If your
tsh db connecterror includes the following text, you likely have an RDS or DocumentDB database created before July 28, 2020, which presents an X.509 certificate that is incompatible with Teleport:x509: certificate relies on legacy Common Name field, use SANs insteadAWS provides instructions to rotate your SSL/TLS certificate.
(!docs/pages/includes/aws-no-credential-provider.mdx service="Database"!)
Timeout errors#
(!docs/pages/includes/database-access/connection-timeout-troubleshooting.mdx!)
Not authorized to perform
sts:AssumeRole#The Database Service assumes an IAM role in one of following situations:
- A Teleport user specifies an IAM role as the database user they wish to use when accessing AWS services that require IAM roles as database users. Databases that support using an IAM role as a database user include: DynamoDB, Keyspaces, Opensearch, Redshift, and Redshift Serverless.
- The
assume_role_arnfield is specified for the database resources or dynamic resource matchers.
What if both situations apply? (role chaining)
When both of the above conditions are true for a database connection, the Database Service performs a role chaining by assuming the IAM role specified in `assume_role_arn` first, then using that IAM role to assume the IAM role for the database user.You may encounter the following error if the trust relationship is not configured properly between the IAM roles:
AccessDenied: User: arn:aws:sts::111111111111:assumed-role/teleport-db-service-role/i-* is not authorized to perform: sts:AssumeRole on resource: arn:aws:iam::111111111111:role/db-user-rolehow to properly configure the trust relationship?
(!docs/pages/includes/database-access/iam_role_trust_relationship.mdx role1="teleport-db-service-role" role2="db-user-role" !)
You can test the trust relationship by running this AWS CLI command as
teleport-db-service-role:$ aws sts assume-role --role-arn arn:aws:iam::111111111111:role/db-user-role --role-session-name test-trust-relationshipLearn more on how to use trust policies with IAM roles.
Maximum policy size exceeded errors#
Due to IAM and STS character limits, you may encounter one of the following errors in the Database Service logs when large numbers of databases are registered:
LimitExceeded: Maximum policy size of 2048 bytes exceeded for user <iam-user>LimitExceeded: Maximum policy size of 10240 bytes exceeded for role <iam-role>
For reference, a user policy can maintain permissions for approximately 6 Redshift databases, or 20 RDS databases due to the IAM policy character limits. A role policy can maintain permissions for approximately 30 Redshift databases, or 100 RDS databases.
To get around this limit, try using one or a combination of the following methods:
Method 1: Organize IAM roles with "assume_role_arn"
You can reduce the policy size by separating them into multiple IAM roles. Use `assume_role_arn` to specify different IAM roles for accessing the databases:Create or print the required IAM policies with the following commands and attach them to the respective IAM roles:
$ teleport db configure aws create-iam --types redshift,redshift-serverless --name teleport-redshift-access $ teleport db configure aws print-iam --types redshift,redshift-serverlessRefer to the command usage for a complete list of database types supported by the
--typesoption.The IAM roles specified in
assume_role_arnmust trust the IAM identity of the host running the Database Service.The
assume_role_arnis not limited to the same AWS account so you can also use this feature for AWS Cross-Account Access.Method 2: Manually manage your IAM policies
You can manually manage IAM policies for database connections instead of relying on the Database Service to update them.For example, you can limit the character size by attaching a policy with a wildcard "*" for "Resource":
You can safely remove the inline policy created by the Database Service and the IAM permissions for the Database Service to
Get/Put/Deletethe user or role policy.Method 3: Separate Database Services
You can deploy the Database Service in a highly available (HA) configuration where databases can be sharded to separate Database Services with different IAM roles.
Method 4: Use IAM roles instead of IAM users
IAM users have a lower character limit compared to IAM roles. If the limit is exceeded for a user policy, it is recommended to use IAM roles for the Database Service instead.
Unable to cancel a query#
If you use a PostgreSQL cli client like
psql, and you try to cancel a query withCtrl+C, but it doesn't cancel the query, then you need to connect using a tsh local proxy instead. Whenpsqlcancels 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 connectwill 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 usingtsh proxy dband connect via the local proxy.If you have already started a long-running query in a
psqlsession that you cannot cancel withCtrl+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_backendandpg_terminate_backendfunctions.SSL SYSCALL error#
You may encounter the following error when your local
psqlis 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: 0Please upgrade your local
psqlto 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.
- 자동 데이터베이스 사용자 프로비저닝을 설정합니다.
