# Database Access with Amazon DynamoDB

Teleport can provide secure access to Amazon DynamoDB 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 DynamoDB database with IAM authentication.
2. Add the database to your Teleport cluster.
3. Connect to the database via Teleport.

## How it works

Teleport users connect to DynamoDB using a local proxy server that forwards requests to the Teleport Database Service via the Teleport Proxy Service. When connecting, the user chooses an IAM role to assume. The Teleport Database Service has permissions to assume this role and potentially other IAM roles. When the Teleport Database Service receives a user request, it rewrites the request with credentials from AWS, then forwards it to the DynamoDB API.

**Self-Hosted**

![DynamoDB Self-Hosted](/docs/assets/images/aws-dynamodb_selfhosted-ffe7105ca3b43d5932a0ff60362f74ac.png)

**Teleport Enterprise Cloud**

![DynamoDB Cloud](/docs/assets/images/aws-dynamodb_cloud-5fab77c08b72d867e7ea0b3ef6057ad8.png)

## Prerequisites

- AWS account with DynamoDB databases.
- IAM permissions to create IAM roles.
- `aws` Command Line Interface (CLI) tool installed in `$PATH`.

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

- A host, e.g., an EC2 instance, where you will run the Teleport Database Service. This guide assumes an EC2 instance when creating and applying IAM roles, and must be adjusted accordingly for custom configurations.
- 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.

This guide provides an example configuration of IAM access roles as a model, and uses an EC2 instance to serve the Teleport Database Service. The level of access provided may not suit your needs, or may not fit your organization's access conventions. You should adjust the AWS IAM permissions to fit your needs.

## Step 1/4. Create IAM roles for DynamoDB access

The setup described in this guide requires two IAM roles:

- One associated with the EC2 instance running the Teleport Database Service, which lets it assume additional roles granted to the user.
- One that can be assumed by the EC2 instance role and grants access to DynamoDB services to users.

### EC2 instance role

Visit the [IAM > Roles page](https://console.aws.amazon.com/iamv2/home#/roles) of the AWS Console, then press "Create Role". Under **Trusted entity type** select "AWS service". Under **Use case** select "EC2", then click **Next**.

![Create Role to Identify EC2 Instance](/docs/assets/images/dynamodb-create-ec2-role-c5e2bc5e7e018b08556152f637d48233.png)

On the "Add Permissions" page, you can simply click **Next** since this role does not require any permissions. In this guide, we will use the example name `TeleportDatabaseService` for this role. Once you have chosen a name, click **Create Role** to complete the process.

### DynamoDB access role

Navigate back to the Roles page and create a new role. Select the "AWS account" option, which creates a default trust policy to allow other entities in this account to assume this role:

![Create Role Step 1](/docs/assets/images/dynamodb-create-role-1-de95f8631ab398d51ab1f49ebf5fb258.png)

Click **Next**. Find the AWS-managed policy `AmazonDynamoDBFullAccess` and then select the policy:

![Create Role Step 2](/docs/assets/images/dynamodb-create-role-2-057c6ad0c7d1fa48bf7de8c6570dd39c.png)

---

APPLY LEAST-PRIVILEGE PERMISSIONS

The `AmazonDynamoDBFullAccess` policy may grant more permissions than desired. If you want to use a different IAM policy to reduce permissions, refer to [Managing access permissions to your Amazon DynamoDB Resources](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/access-control-overview.html) for more information.

---

Click **Next**. On the next page, enter a role name. In this guide we'll use the example name `ExampleTeleportDynamoDBRole` for this role.

Under "Select trusted entities", update the JSON to allow the `TeleportDatabaseService` role to assume this role:

```
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": [
                    "arn:aws:iam::abcd1234-this-is-an-example:role/TeleportDatabaseService"
                ]
            },
            "Action": "sts:AssumeRole",
            "Condition": {}
        }
    ]
}

```

Finally, click **Create Role**.

## Step 2/4. Configure the Teleport IAM role mapping

The next step is to give your Teleport users permissions to assume AWS IAM roles when accessing AWS resources through your Teleport cluster.

You can do this by creating a Teleport role with the `db_users` field listing the IAM role ARN created in the previous step. Create a file called `aws-dynamodb-access.yaml` with the following content:

```
kind: role
version: v7
metadata:
  name: aws-dynamodb-access
spec:
  allow:
    db_labels:
      '*': '*'
    db_users:
    - 'ExampleTeleportDynamoDBRole'

```

Create the new role:

```
$ tctl create -f aws-dynamodb-access.yaml
```

---

TIP

You can also create and edit roles using the Web UI. Go to **Access -> Roles** and click **Create New Role** or pick an existing role to edit.

---

Assign the `aws-dynamodb-access` role to your Teleport user by running the appropriate commands for your authentication provider:

**Local User**

1. Retrieve your local user's roles as a comma-separated list:

   ```
   $ ROLES=$(tsh status -f json | jq -r '.active.roles | join(",")')
   ```

2. Edit your local user to add the new role:

   ```
   $ tctl users update $(tsh status -f json | jq -r '.active.username') \
     --set-roles "${ROLES?},aws-dynamodb-access"
   ```

3. Sign out of the Teleport cluster and sign in again to assume the new role.

**GitHub**

1. Open your `github` authentication connector in a text editor:

   ```
   $ tctl edit github/github
   ```

2. Edit the `github` connector, adding `aws-dynamodb-access` to the `teams_to_roles` section.

   The team you should map to this role depends on how you have designed your organization's role-based access controls (RBAC). However, the team must include your user account and should be the smallest team possible within your organization.

   Here is an example:

   ```
     teams_to_roles:
       - organization: octocats
         team: admins
         roles:
           - access
   +       - aws-dynamodb-access

   ```

3. Apply your changes by saving and closing the file in your editor.

4. Sign out of the Teleport cluster and sign in again to assume the new role.

**SAML**

1. Retrieve your `saml` configuration resource:

   ```
   $ tctl get --with-secrets saml/mysaml > saml.yaml
   ```

   Note that the `--with-secrets` flag adds the value of `spec.signing_key_pair.private_key` to the `saml.yaml` file. Because this key contains a sensitive value, you should remove the saml.yaml file immediately after updating the resource.

2. Edit `saml.yaml`, adding `aws-dynamodb-access` to the `attributes_to_roles` section.

   The attribute you should map to this role depends on how you have designed your organization's role-based access controls (RBAC). However, the group must include your user account and should be the smallest group possible within your organization.

   Here is an example:

   ```
     attributes_to_roles:
       - name: "groups"
         value: "my-group"
         roles:
           - access
   +       - aws-dynamodb-access

   ```

3. Apply your changes:

   ```
   $ tctl create -f saml.yaml
   ```

4. Sign out of the Teleport cluster and sign in again to assume the new role.

**OIDC**

1. Retrieve your `oidc` configuration resource:

   ```
   $ tctl get oidc/myoidc --with-secrets > oidc.yaml
   ```

   Note that the `--with-secrets` flag adds the value of `spec.signing_key_pair.private_key` to the `oidc.yaml` file. Because this key contains a sensitive value, you should remove the oidc.yaml file immediately after updating the resource.

2. Edit `oidc.yaml`, adding `aws-dynamodb-access` to the `claims_to_roles` section.

   The claim you should map to this role depends on how you have designed your organization's role-based access controls (RBAC). However, the group must include your user account and should be the smallest group possible within your organization.

   Here is an example:

   ```
     claims_to_roles:
       - name: "groups"
         value: "my-group"
         roles:
           - access
   +       - aws-dynamodb-access

   ```

3. Apply your changes:

   ```
   $ tctl create -f oidc.yaml
   ```

4. Sign out of the Teleport cluster and sign in again to assume the new role.

## Step 3/4. Install the Teleport Database Service

Create an EC2 instance to host the Teleport Database Service, and attach the `TeleportDatabaseService` AWS IAM role to it. If you're hosting the service another way, you must provide AWS credentials to the service - see [AWS credentials configuration](https://docs.aws.amazon.com/sdkref/latest/guide/creds-config-files.html) for more details.

---

NON-STANDARD AWS REGIONS

For non-standard AWS regions such as AWS GovCloud (US) regions and AWS China regions, please set the corresponding region in the `AWS_REGION` environment variable or in the AWS credentials file so that the Database Service can use the correct STS endpoint.

---

### Generate a token

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)

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

### Install and start 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
   ```

Create a file called `/etc/teleport.yaml` with the following content:

```
version: v3
teleport:
  nodename: CHANGEME
  data_dir: /var/lib/teleport
  proxy_server: teleport.example.com:443
  auth_token: /tmp/token
db_service:
  enabled: true
  # Lists statically registered databases proxied by this agent.
  databases:
    - name: "example-dynamodb"
      protocol: "dynamodb"
      # optional uri, if uri is set then AWS region can be extracted from it
      # or if AWS region is already set then the regions must match.
      # uri: "dynamodb.us-east-1.amazonaws.com:443"
      static_labels:
        env: "dev"
      aws:
        region: "us-east-1"
        account_id: "abcd1234-this-is-an-example"

```

Substitute `teleport.example.com` with the address of your Teleport Proxy Service. (For Teleport Cloud customers, this will be similar to `mytenant.teleport.sh`.) The token generated should have been placed in the file `/tmp/token`.

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 4/4 Connect

Once the Database Service has started and joined the cluster, you can start connecting to your DynamoDB database.

Create a proxy tunnel:

```
$ tsh proxy db --tunnel --port 8000 --db-user=ExampleTeleportDynamoDBRole example-dynamodb
```

You can test the connection to the database through the `aws` CLI:

```
$ aws dynamodb list-tables --endpoint-url=http://localhost:8000
{
    "TableNames": [
        "table1",
        "table2",
        "table3"
    ]
}
```

You can also connect to this database from the AWS NoSQL Workbench, as documented in our [Database Access GUI Clients](https://goteleport.com/docs/connect-your-client/third-party/gui-clients.md#nosql-workbench) guide.

You can also use this tunnel for programmatic access. The example below uses the `boto3` SDK from AWS:

```
$ python3
Python 3.10.4 (main, Mar 31 2022, 03:37:37) [Clang 12.0.0 ] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import boto3
>>> clt = boto3.client('dynamodb', endpoint_url='http://localhost:8000')
>>> res = clt.list_tables()
>>> print(res)
{'TableNames': *snip output*}
>>>

```

## Next Steps

- See [Dynamic Database Registration](https://goteleport.com/docs/enroll-resources/database-access/guides/dynamic-registration.md) to learn how to use resource labels to keep Teleport up to date with accessible databases in your infrastructure.
