# Database Access with Amazon RDS Proxy for SQL Server

Teleport can provide secure access to Amazon RDS proxy for Microsoft SQL Server 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 Amazon RDS proxy for Microsoft SQL Server database with IAM authentication.
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 RDS Proxy. 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.

**Self-Hosted**

![Teleport Architecture RDS Proxy Self-Hosted](/docs/assets/images/rds-proxy_selfhosted-4a48ade2c71f6b7fe3e23f13342fd146.png)

**Cloud-Hosted**

![Teleport Architecture RDS Proxy Cloud-Hosted](/docs/assets/images/rds-proxy_cloud-c701f343cf6664433773f2a4e6c95eee.png)

---

SUPPORTED ENGINE FAMILY

Teleport currently supports RDS Proxy instances with engine family [PostgreSQL](https://goteleport.com/docs/enroll-resources/database-access/enrollment/aws/rds-proxy/rds-proxy-postgres.md), [MariaDB/MySQL](https://goteleport.com/docs/enroll-resources/database-access/enrollment/aws/rds-proxy/rds-proxy-postgres.md) or [Microsoft SQL Server](https://goteleport.com/docs/enroll-resources/database-access/enrollment/aws/rds-proxy/rds-proxy-sqlserver.md).

---

This guide shows how to register a single RDS Proxy with your Teleport cluster. For a more scalable approach, learn how to set up [Database Auto-Discovery](https://goteleport.com/docs/enroll-resources/auto-discovery/databases.md) to automatically enroll all AWS databases in your infrastructure.

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

* AWS account with RDS Proxy instances and permissions to create and attach IAM policies.
* Any RDS Proxy instances intended for connection through Teleport must have TLS enabled.
* A host, e.g., an EC2 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  18.7.3
  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/6. 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 2/6. Create a Teleport Database Service configuration

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

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:

- [Configure Teleport to Automatically Enroll EC2 instances](https://goteleport.com/docs/enroll-resources/auto-discovery/servers/ec2-discovery.md)
- [Joining Teleport Services via AWS IAM Role](https://goteleport.com/docs/enroll-resources/agents/aws-iam.md)
- [Joining Teleport Services via AWS EC2 Identity Document](https://goteleport.com/docs/enroll-resources/agents/aws-ec2.md)

Create the Database Service configuration. Replace teleport.example.com:443 with the domain name **and port** of your Teleport Proxy Service or cloud-hosted Teleport Enterprise account and endpoint:port with the host **and port** of the database endpoint:

```
$ sudo teleport db configure create \
   -o file \
   --proxy=teleport.example.com:443 \
   --uri=endpoint:port \
   --protocol=sqlserver \
   --token=/tmp/token \
   --labels=env=dev
```

The command will generate a Teleport Database Service configuration file and place it at the `/etc/teleport.yaml` location.

## Step 3/6. Configure Database Service IAM permissions

The Teleport Database Service needs AWS IAM permissions to provide access to RDS Proxy instances.

### Create an IAM role for Teleport

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

**Instance Metadata Service**

Teleport will detect when it is running on an EC2 instance and use the Instance Metadata Service to fetch credentials.

The EC2 instance should be configured to use an EC2 instance profile. For more information, see: [Using Instance Profiles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2_instance-profiles.html).

**Kubernetes IRSA**

Refer to [IAM Roles for Service Accounts (IRSA)](https://docs.aws.amazon.com/eks/latest/userguide/iam-roles-for-service-accounts.html) to set up an OIDC provider in AWS and configure an AWS IAM role that allows the pod's service account to assume the role.

**Environment Variables**

Teleport's built-in AWS client reads credentials from the following environment variables:

- `AWS_ACCESS_KEY_ID`
- `AWS_SECRET_ACCESS_KEY`
- `AWS_DEFAULT_REGION`

When you start the Database Service, the service reads environment variables from a file at the path `/etc/default/teleport`. Obtain these credentials from your organization. Ensure that `/etc/default/teleport` has the following content, replacing the values of each variable:

```
AWS_ACCESS_KEY_ID=00000000000000000000
AWS_SECRET_ACCESS_KEY=0000000000000000000000000000000000000000
AWS_DEFAULT_REGION=<YOUR_REGION>

```

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_PROFILE` environment 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](https://docs.aws.amazon.com/sdk-for-go/api/aws/session/) for a detailed description of credential loading behavior.

### Grant permissions

Attach the following AWS IAM permissions to the Database Service IAM role:

```
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "RDSProxyConnect",
            "Effect": "Allow",
            "Action": "rds-db:connect",
            "Resource": "*"
        },
        {
            "Sid": "RDSProxyFetchMetadata",
            "Effect": "Allow",
            "Action": [
                "rds:DescribeDBProxies",
                "rds:DescribeDBProxyEndpoints"
            ],
            "Resource": "*"
        }
    ]
}

```

| Statement               | Purpose                                                                                                         |
| ----------------------- | --------------------------------------------------------------------------------------------------------------- |
| `RDSProxyConnect`       | Generate an IAM authentication token to connect to a database.                                                  |
| `RDSProxyFetchMetadata` | Automatically import AWS tags as database labels or find missing information such as the database's AWS region. |

The `rds-db:connect` permission is required to connect to databases. You can reduce the scope of the permission to only allow specific databases, regions, or users. The resource ARN has the following format:

```
arn:aws:rds-db:{Region}:{AccountID}:dbuser:{ResourceID}/{UserName}
```

Refer to [Creating and using an IAM policy for IAM database access](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.IAMPolicy.html) for more information about the `rds-db:connect` permission grant syntax.

Databases discovered by the Teleport Discovery Service should be registered with complete metadata, so you can also omit the `RDSProxyFetchMetadata` permissions if all of your AWS databases are being auto-discovered.

## Step 4/6. Start the 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 5/6. Configure database user credentials

The Database Service connects to an RDS Proxy instance using IAM authentication. In addition, the RDS Proxy instance must also be able to connect to the RDS DB instance or Aurora DB cluster using pre-configured database user credentials.

First, use Secrets Manager to store sets of user name and password credentials. You create a separate Secrets Manager secret for each database user account that RDS Proxy connects to on the RDS DB instance or Aurora DB cluster. The password associated with the secret must match the database password for that user in the target database.

For example, the following AWS CLI command creates a Secrets Manager secret for database user `alice`:

```
$ aws secretsmanager create-secret \
  --name rdsproxy_alice --description "database user alice" \
  --secret-string '{"username":"alice","password":"password_for_alice"}'
```

Next, create an IAM role with a policy that can access these secrets, for example:

```
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "secretsmanager:GetSecretValue",
            "Resource": [
                "arn:aws:secretsmanager:us-west-1:account_id:secret:rdsproxy_alice",
                "arn:aws:secretsmanager:us-west-1:account_id:secret:rdsproxy_anotheruser"
            ]
        },
        {   
            "Effect": "Allow",
            "Action": "kms:Decrypt",
            "Resource": "arn:aws:kms:us-west-1:account_id:key/key_id",
            "Condition": {
                "StringEquals": {
                    "kms:ViaService": "secretsmanager.us-east-2.amazonaws.com"
                }
            }
        }
    ]
}

```

The IAM role should have the following trust policy:

```
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": {
        "Service": "rds.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

```

Lastly, modify the RDS Proxy authentication settings to use the created IAM role and Secrets Manager secrets. Make sure IAM authentication is set to **Required**:

![RDS Proxy Authentication](/docs/assets/images/rds-proxy_auth-e146967693a38a97ad776eda2f002ae7.png)

---

IAM AUTHENTICATION PER DATABASE USER

If you need to disable IAM authentication for some database users that are not intended for Teleport access, use the following AWS CLI command to set **IAMAuth** *per secret*:

```
$ aws rds modify-db-proxy --db-proxy-name my-rds-proxy --auth AuthScheme=SECRETS,SecretArn=arn-of-teleport-access-user,\
IAMAuth=REQUIRED AuthScheme=SECRETS,SecretArn=arn-of-non-teleport-user,IAMAuth=DISABLED ...
```

See `aws rds modify-db-proxy help` for more information.

---

## Step 6/6. Connect

Once the Database Service has started and joined the cluster, log in to see the registered database:

```
$ tsh login --proxy=teleport.example.com:443 --user=alice
$ tsh db ls
Name                         Description                     Labels
---------------------------- ------------------------------- -------
rds-proxy                    RDS Proxy in us-west-1          ...
```

Retrieve credentials for the database and connect to it as the `alice` user:

```
$ tsh db connect --db-user=alice --db-name=dev rds-proxy
```

---

TIP

You can also [access your PostgreSQL and 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:

```
$ tsh db logout rds-proxy
```

## Troubleshooting

### Certificate error

If your `tsh db connect` error 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 instead

```

AWS provides instructions to rotate your [SSL/TLS certificate](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.SSL-certificate-rotation.html).

### No credential providers error

If you see the error `NoCredentialProviders: no valid providers in chain` in Database Service logs then Teleport is not detecting the required credentials to connect via AWS IAM permissions. Check whether the credentials or security role has been applied in the machine running the Teleport Database Service.

When running on EKS, this error may occur if the Teleport Database Service cannot access IMDSv2 when the PUT requests hop limit on the worker node instance is set to 1. You can use the following commands to check the hop limit:

```
$ aws ec2 describe-instances --instance-ids <node-instance-id> | grep HttpPutResponseHopLimit
                        "HttpPutResponseHopLimit": 1,
```

See [IMDSv2 support for EKS](https://aws.amazon.com/about-aws/whats-new/2020/08/amazon-eks-supports-ec2-instance-metadata-service-v2/) and [EKS best practices](https://aws.github.io/aws-eks-best-practices/security/docs/iam/#when-your-application-needs-access-to-imds-use-imdsv2-and-increase-the-hop-limit-on-ec2-instances-to-2) for more details.

### Timeout errors

The Teleport Database Service requires connectivity to your database endpoints.

Check that firewall rules (e.g., AWS security groups) allow connectivity between the Teleport Database Service and the database endpoint.

- Inbound firewall rules for the database must allow connections from the Teleport Database Service.
- Outbound firewall rules for the Teleport Database Service must allow connections to the database endpoint.

---

TIP

On the same host as the Teleport Database Service, try running `nc` to check if it can reach the database port.

- Database host: database-host
- Database port: database-port

```
$ nc -zv database-host database-port
Connection to postgres-instance-1.sadas.us-east-1.rds.amazonaws.com (172.31.24.172) 5432 port [tcp/postgresql] succeeded!
```

---

Debugging connection timeout errors in AWS

For deployments in AWS, it may be helpful to use [AWS Reachability Analyzer](https://docs.aws.amazon.com/vpc/latest/reachability/what-is-reachability-analyzer.html) to analyze the network path between the Teleport Database Service and the database.

1. Identify the Elastic Network Interface (ENI) associated with the Teleport Database Service host. This can be found in the [EC2 console](https://console.aws.amazon.com/ec2/home?NIC).

2. Identify the private IP address of the database.

3. Create and analyze a network path:

   - Set the path source to the ENI associated with the Teleport Database Service host.
   - Set the path destination to the database IP.

4. Check the analysis results to identify reachability issues.

If your database is registered dynamically or via auto-discovery, repeat the above connectivity test for *every*\* Teleport Database Service instance that proxies this database. To list all Teleport Database Service instances associated with a given database, run the `tctl get db_server/<db_name>` command. For example:

```
$ tctl get db_server/postgres-instance-1 --format json | jq '.[] | {hostname: .spec.hostname, host_id: .spec.host_id, version: .spec.version, target_health: .status.target_health}'
{
  "hostname": "ip-10-0-0-111.ca-central-1.compute.internal",
  "host_id": "e5e670ac-a7b8-44ef-b373-6296d87f50e8",
  "version": "18.3.0",
  "target_health": {
    "status": "unhealthy",
    ...
  }
}
{
  "hostname": "ip-10-0-0-222.ca-central-1.compute.internal",
  ...
}

```

If any of the Database Service instances listed here **should not** proxy the database, (for example, a Database Service instance in a different VPC or AWS region without connectivity), locate and update their configurations so they only receive or discover databases they can reach. In most cases, you can achieve this by refining your tag filters, such as adding the `vpc-id` label.

### 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_arn` field 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-role

```

how to properly configure the trust relationship?

To allow IAM Role `teleport-db-service-role` to assume IAM Role `db-user-role`, the following is generally required:

**1. Configure Trust Relationships on db-user-role**

`teleport-db-service-role` or its AWS account should be set as `Principal` in `db-user-role`'s trust policy.

**Role as principal**

Assign aws-account-id to your AWS account ID:

```
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::aws-account-id:role/teleport-db-service-role"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

```

**Account as principal**

Assign aws-account-id to your AWS account ID:

```
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::aws-account-id:root"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

```

**Cross-account with external-id**

Assign external-aws-account-id to an external AWS account ID:

```
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::external-aws-account-id:role/teleport-db-service-role"
      },
      "Action": "sts:AssumeRole",
      "Condition": {
        "StringEquals": {
          "sts:ExternalId": "example-external-id"
        }
      }
    }
  ]
}

```

**2. Configure Permissions Policies on teleport-db-service-role**

`teleport-db-service-role` requires `sts:AssumeRole` permissions, for example:

```
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": "sts:AssumeRole",
            "Effect": "Allow",
            "Resource": "arn:aws:iam::aws-account-id:role/db-user-role"
        }
    ]
}

```

Note that this policy can be omitted when `teleport-db-service-role` and `db-user-role` are in the same AWS account and `teleport-db-service-role`'s full ARN is configured as Principal in `db-user-role`'s trust policy.

**3. Configure Permissions Boundary on teleport-db-service-role**

If `teleport-db-service-role` does not have an attached [Permissions boundary](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html) then you can skip this step. Otherwise, the boundary policy attached to `teleport-db-service-role` must include `sts:AssumeRole` permissions, for example:

```
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": "sts:AssumeRole",
            "Effect": "Allow",
            "Resource": "*"
        }
    ]
}

```

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

Learn more on [how to use trust policies with IAM roles](https://aws.amazon.com/blogs/security/how-to-use-trust-policies-with-iam-roles/).

### Maximum policy size exceeded errors

Due to [IAM and STS character limits](https://docs.aws.amazon.com/iam/latest/userguide/reference_iam-quotas.html#reference_iam-quotas-entity-length), 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:

**Auto-Discovery by Discovery Service**

You can specify `assume_role_arn` in the AWS matchers of Discovery Service's configuration:

---

WARNING

Discovery Service exposes a configuration parameter - `discovery_service.discovery_group` - that allows you to group discovered resources into different sets. This parameter is used to prevent Discovery Agents watching different sets of cloud resources from colliding against each other and deleting resources created by another services.

When running multiple Discovery Services, you must ensure that each service is configured with the same `discovery_group` value if they are watching the same cloud resources or a different value if they are watching different cloud resources.

It is possible to run a mix of configurations in the same Teleport cluster meaning that some Discovery Services can be configured to watch the same cloud resources while others watch different resources. As an example, a 4-agent high availability configuration analyzing data from two different cloud accounts would run with the following configuration.

- 2 Discovery Services configured with `discovery_group: "prod"` polling data from Production account.
- 2 Discovery Services configured with `discovery_group: "staging"` polling data from Staging account.

---

```
discovery_service:
  discovery_group: "prod"
  enabled: true
  aws:
    - types: ["rds"]
      regions: ["us-west-1", "us-west-2"]
      assume_role_arn: "arn:aws:iam::123456789012:role/example-role-rds-env-prod-discovery"
      tags:
        "env": "prod"

    - types: ["redshift", "redshift-serverless"]
      regions: ["us-west-2"]
      assume_role_arn: "arn:aws:iam::123456789012:role/example-role-redshift-env-dev"
      tags:
        "env": "dev"

```

The Discovery Service will use the IAM roles specified in `assume_role_arn` for discovery, and by default the Database Service will use the same IAM roles for authentication.

However, you can also overwrite the IAM roles for authentication by Database Service if you wish to use different roles:

```
db_service:
  enabled: true
  resources:
    # Matches us-west-1 env=prod RDS databases from Discovery Service, and
    # overwrites assume_role_arn.
    - labels:
        "env": "prod"
        "region": "us-west-1"
      aws:
        assume_role_arn: "arn:aws:iam::123456789012:role/example-role-rds-env-prod-us-west-1-access"

    # Matches us-west-2 env=prod RDS databases from Discovery Service, and
    # overwrites assume_role_arn.
    - labels:
        "env": "prod"
        "region": "us-west-2"
      aws:
        assume_role_arn: "arn:aws:iam::123456789012:role/example-role-rds-env-prod-us-west-2-access"

    # Matches env=dev Redshift databases from Discovery Service and inherits
    # "arn:aws:iam::123456789012:role/example-role-redshift-env-dev"
    - labels:
        "env": "dev"

```

---

AUTO-DISCOVERY LABELS

Teleport generates certain labels derived from the cloud resource attributes during discovery. See [Auto-Discovery labels](https://goteleport.com/docs/enroll-resources/database-access/reference/labels.md) /labels/#auto-discovery) for more details.

---

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

Refer to the command usage for a complete list of database types supported by the `--types` option.

**Auto-Discovery by Database Service**

You can specify `assume_role_arn` in the AWS matchers of Database Service's configuration:

```
db_service:
  enabled: true
  aws:
    - types: ["rds"]
      regions: ["us-west-1", "us-west-2"]
      assume_role_arn: "arn:aws:iam::123456789012:role/example-role-rds-env-prod"
      tags:
        "env": "prod"

    - types: ["redshift", "redshift-serverless"]
      regions: ["us-west-2"]
      assume_role_arn: "arn:aws:iam::123456789012:role/example-role-redshift-env-dev"
      tags:
        "env": "dev"

```

The Database Service will use the IAM roles specified `assume_role_arn` for both discovery and authentication.

To bootstrap IAM permissions, run the bootstrap command for each `assume_role_arn`:

```
$ teleport db configure bootstrap \
    -c /etc/teleport.yaml \
    --policy-name teleport-policy-rds-env-prod \
    --attach-to-role "arn:aws:iam::123456789012:role/example-role-rds-env-prod"
```

**Static config**

You can specify `aws.assume_role_arn` when defining databases in Database Service's configuration:

```
db_service:
  enabled: true
  databases:
  - name: "rds-postgres"
    protocol: "postgres"
    uri: "rds-postgres.abcdef012345.us-west-1.rds.amazonaws.com:5432"
    aws:
        assume_role_arn: "arn:aws:iam::123456789012:role/example-rds-access-role"

```

To bootstrap IAM permissions, run the bootstrap command for each `assume_role_arn`:

```
$ teleport db configure bootstrap \
    -c /etc/teleport.yaml \
    --policy-name teleport-policy-rds-access \
    --attach-to-role "arn:aws:iam::123456789012:role/example-rds-access-role"
```

**Other dynamic resources**

You can specify `aws.assume_role_arn` when defining databases:

```
kind: db
version: v3
metadata:
  name: "rds-postgres"
  labels:
    env: "dev"
spec:
  protocol: "postgres"
  uri: "rds-postgres.abcdef012345.us-west-1.rds.amazonaws.com:5432"
  aws:
    assume_role_arn: "arn:aws:iam::123456789012:role/example-rds-access-role"

```

Alternatively, you can overwrite the IAM roles for authentication by Database Service:

```
db_service:
  enabled: true
  resources:
    # Matches env=dev databases and overwrites assume_role_arn.
    - labels:
        "env": "dev"
      aws:
        assume_role_arn: "arn:aws:iam::123456789012:role/example-env-dev-access"

    # Matches env=prod database, and use the assume_role_arn in the database's
    # definition or use the host IAM identity if assume_role_arn is empty.
    - labels:
        "env": "prod"

```

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 rds --name teleport-rds-access
$ teleport db configure aws print-iam --types rds
```

Refer to the command usage for a complete list of database types supported by the `--types` option.

The IAM roles specified in `assume_role_arn` must [trust](https://aws.amazon.com/blogs/security/how-to-use-trust-policies-with-iam-roles/) the IAM identity of the host running the Database Service.

The `assume_role_arn` is not limited to the same AWS account so you can also use this feature for [AWS Cross-Account Access](https://goteleport.com/docs/enroll-resources/database-access/enrollment/aws/aws-cross-account.md).

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

**RDS or RDS Proxy**

```
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "rds-db:connect",
            "Resource": "*"
        }
    ]
}

```

**Redshift**

```
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "redshift:GetClusterCredentials",
            "Resource": "*"
        }
    ]
}

```

You can safely remove the inline policy created by the Database Service and the IAM permissions for the Database Service to `Get/Put/Delete` the user or role policy.

Method 3: Separate Database Services

You can deploy [the Database Service in a highly available (HA) configuration](https://goteleport.com/docs/enroll-resources/agents/high-availability.md) 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.

## 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 on [Setting up database credentials in AWS Secrets Manager](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/rds-proxy-setup.html) and [Setting up AWS Identity and Access Management (IAM) policies](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/rds-proxy-setup.html) for RDS Proxy
