

# Accessing Amazon Keyspaces (for Apache Cassandra)
<a name="accessing"></a>

You can access Amazon Keyspaces using the console, AWS CloudShell, programmatically by running a `cqlsh` client, the AWS SDK, or by using an Apache 2.0 licensed Cassandra driver. Amazon Keyspaces supports drivers and clients that are compatible with Apache Cassandra 3.11.2. Before accessing Amazon Keyspaces, you must complete setting up AWS Identity and Access Management and then grant an IAM identity access permissions to Amazon Keyspaces.

## Setting up AWS Identity and Access Management
<a name="SettingUp.IAM"></a>

### Sign up for an AWS account
<a name="sign-up-for-aws"></a>

If you do not have an AWS account, complete the following steps to create one.

**To sign up for an AWS account**

1. Open [https://portal.aws.amazon.com/billing/signup](https://portal.aws.amazon.com/billing/signup).

1. Follow the online instructions.

   Part of the sign-up procedure involves receiving a phone call or text message and entering a verification code on the phone keypad.

   When you sign up for an AWS account, an *AWS account root user* is created. The root user has access to all AWS services and resources in the account. As a security best practice, assign administrative access to a user, and use only the root user to perform [tasks that require root user access](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html#root-user-tasks).

AWS sends you a confirmation email after the sign-up process is complete. At any time, you can view your current account activity and manage your account by going to [https://aws.amazon.com/](https://aws.amazon.com/) and choosing **My Account**.

### Create a user with administrative access
<a name="create-an-admin"></a>

After you sign up for an AWS account, secure your AWS account root user, enable AWS IAM Identity Center, and create an administrative user so that you don't use the root user for everyday tasks.

**Secure your AWS account root user**

1.  Sign in to the [AWS Management Console](https://console.aws.amazon.com/) as the account owner by choosing **Root user** and entering your AWS account email address. On the next page, enter your password.

   For help signing in by using root user, see [Signing in as the root user](https://docs.aws.amazon.com/signin/latest/userguide/console-sign-in-tutorials.html#introduction-to-root-user-sign-in-tutorial) in the *AWS Sign-In User Guide*.

1. Turn on multi-factor authentication (MFA) for your root user.

   For instructions, see [Enable a virtual MFA device for your AWS account root user (console)](https://docs.aws.amazon.com/IAM/latest/UserGuide/enable-virt-mfa-for-root.html) in the *IAM User Guide*.

**Create a user with administrative access**

1. Enable IAM Identity Center.

   For instructions, see [Enabling AWS IAM Identity Center](https://docs.aws.amazon.com//singlesignon/latest/userguide/get-set-up-for-idc.html) in the *AWS IAM Identity Center User Guide*.

1. In IAM Identity Center, grant administrative access to a user.

   For a tutorial about using the IAM Identity Center directory as your identity source, see [ Configure user access with the default IAM Identity Center directory](https://docs.aws.amazon.com//singlesignon/latest/userguide/quick-start-default-idc.html) in the *AWS IAM Identity Center User Guide*.

**Sign in as the user with administrative access**
+ To sign in with your IAM Identity Center user, use the sign-in URL that was sent to your email address when you created the IAM Identity Center user.

  For help signing in using an IAM Identity Center user, see [Signing in to the AWS access portal](https://docs.aws.amazon.com/signin/latest/userguide/iam-id-center-sign-in-tutorial.html) in the *AWS Sign-In User Guide*.

**Assign access to additional users**

1. In IAM Identity Center, create a permission set that follows the best practice of applying least-privilege permissions.

   For instructions, see [ Create a permission set](https://docs.aws.amazon.com//singlesignon/latest/userguide/get-started-create-a-permission-set.html) in the *AWS IAM Identity Center User Guide*.

1. Assign users to a group, and then assign single sign-on access to the group.

   For instructions, see [ Add groups](https://docs.aws.amazon.com//singlesignon/latest/userguide/addgroups.html) in the *AWS IAM Identity Center User Guide*.

## Setting up Amazon Keyspaces
<a name="SettingUp.KEY"></a>

 Access to Amazon Keyspaces resources is managed using [ IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html). Using IAM, you can attach policies to IAM users, roles, and federated identities that grant read and write permissions to specific resources in Amazon Keyspaces. 

To get started with granting permissions to an IAM identity, you can use one of the AWS managed policies for Amazon Keyspaces:
+ [AmazonKeyspacesFullAccess](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonKeyspacesFullAccess.html) – this policy grants permissions to access all resources in Amazon Keyspaces with full access to all features.
+ [AmazonKeyspacesReadOnlyAccess\$1v2](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonKeyspacesReadOnlyAccess_v2.html) – this policy grants read-only permissions to Amazon Keyspaces.

For a detailed explanation of the actions defined in the managed policies, see [AWS managed policies for Amazon Keyspaces](security-iam-awsmanpol.md).

To limit the scope of actions that an IAM identity can perform or limit the resources that the identity can access, you can create a custom policy that uses the `AmazonKeyspacesFullAccess` managed policy as a template and remove all permissions that you don't need. You can also limit access to specific keyspaces or tables. For more information about how to restrict actions or limit access to specific resources in Amazon Keyspaces, see [How Amazon Keyspaces works with IAM](security_iam_service-with-iam.md). 

To access Amazon Keyspaces after you have created the AWS account and created a policy that grants an IAM identity access to Amazon Keyspaces, continue to one of the following sections:
+ [Using the console](console_keyspaces.md)
+ [Using AWS CloudShell](using-aws-with-cloudshell.md)

# Accessing Amazon Keyspaces using the console
<a name="console_keyspaces"></a>

You can access the console for Amazon Keyspaces at [https://console.aws.amazon.com/keyspaces/home](https://console.aws.amazon.com/keyspaces/home). For more information about AWS Management Console access, see [Controlling IAM users access to the AWS Management Console](https://docs.aws.amazon.com/IAM/latest/UserGuide/console_controlling-access.html) in the IAM User Guide.

You can use the console to do the following in Amazon Keyspaces:
+ Create, delete, and manage keyspaces and tables.
+ Monitor important table metrics on a table's **Monitor** tab:
  + Billable table size (Bytes)
  + Capacity metrics
+ Run queries using the CQL editor or through the [integrated AWS CloudShell experience](console_cloudshell_integration.md), for example insert, update, and delete data.
+ Connect to Amazon Keyspaces directly through AWS CloudShell with integrated CQLSH support.
+ Change the partitioner configuration of the account.
+ View performance and error metrics for the account on the dashboard.

# Connect to Amazon Keyspaces using AWS CloudShell from the console
<a name="console_cloudshell_integration"></a>

AWS CloudShell provides a streamlined way to connect to Amazon Keyspaces directly from the console. The AWS CloudShell integration automatically initializes the `cqlsh-expansion` for you and establishes a connection to a specific keyspace.

## Getting started with AWS CloudShell integration
<a name="cloudshell_getting_started"></a>

1. **Access the AWS CloudShell integration** – From the Amazon Keyspaces console, navigate to the keyspace you want to connect to and choose the **Connect to Keyspaces** AWS CloudShell button.

1. **Pre-filled setup command** – When you choose the AWS CloudShell button, the system provides a pre-filled command that includes the necessary initialization and connection parameters:

   ```
   cqlsh-expansion.init ; cqlsh-expansion cassandra.region.amazonaws.com 9142 --ssl -my_keyspace
   ```

1. **Click **Run****

1. **Wait for Amazon Keyspaces to establish the connection** – Allow time for the setup process to complete and the connection to your selected keyspace to be established.

1. **Execute commands** – When connected, you can write and execute CQL commands directly against the selected keyspace.

## Available CQLSH commands
<a name="available_cqlsh_commands"></a>

The AWS CloudShell integration provides access to standard CQLSH functionality, including support for commands beyond basic CQL.
+ **Describe** – List and view detailed descriptions of keyspaces and tables.
+ **Copy** – Export query output to a file for later processing.
+ **Source** – Execute CQL statements from a file.
+ **Command history navigation** – Scroll through previous commands using keyboard shortcuts.
+ **Query execution** – Run queries directly from the keyboard interface.
+ **Output copying** – Copy results as simple text for use in other applications.

## Feature considerations
<a name="feature_considerations"></a>

When using the AWS CloudShell integration, consider the following trade-offs.

**The following features are not supported:**
+ CQL syntax suggestions and auto-complete functionality.
+ Editor tools such as show autocomplete, show tooltip, find, find and replace, redo, toggle block comments, toggle code folding, toggle line comment, and undo.

**Modified functionality:**
+ **CSV downloads** – To download results as CSV format, specify the `>` operator to pipe command output:

  ```
  SELECT * FROM my_table > file_name.csv
  ```
+ **JSON viewing** - You can view items in JSON format without requiring data conversion.
+ **Terminal-style interface** - The experience operates as a terminal interface rather than a full-featured code editor.

The AWS CloudShell integration simplifies the connection process while providing essential CQL functionality for managing your Amazon Keyspaces data directly from the AWS Management Console.

To learn how to create an Amazon Keyspaces keyspace and table and set it up with sample application data, see [Getting started with Amazon Keyspaces (for Apache Cassandra)](getting-started.md). 

# Using AWS CloudShell to access Amazon Keyspaces
<a name="using-aws-with-cloudshell"></a>

AWS CloudShell is a browser-based, pre-authenticated shell that you can launch directly from the AWS Management Console. You can run AWS CLI commands against AWS services using your preferred shell (Bash, PowerShell or Z shell). AWS CloudShell comes pre-authenticated with your console credentials and includes common tools for working with AWS services, including the AWS CLI, Python, and Node.js.

You [launch AWS CloudShell from the AWS Management Console](https://docs.aws.amazon.com/cloudshell/latest/userguide/working-with-cloudshell.html#launch-options), and the AWS credentials you used to sign in to the console are automatically available in a new shell session. This pre-authentication of AWS CloudShell users allows you to skip configuring credentials when interacting with AWS services such as Amazon Keyspaces using `cqlsh` or AWS CLI version 2 (pre-installed on the shell's compute environment).

## AWS CloudShell integration options
<a name="cloudshell-integration-options"></a>

Amazon Keyspaces offers two ways to use AWS CloudShell:

1. **Integrated AWS CloudShell experience** - A streamlined connection method available directly from the Amazon Keyspaces console that automatically initializes the `cqlsh-expansion` and connects to a specific keyspace. For complete instructions on using this integrated experience, see [Connect to Amazon Keyspaces using AWS CloudShell from the console](console_cloudshell_integration.md).

1. **Manual AWS CloudShell setup** - Manually install and configure `cqlsh` in AWS CloudShell. The steps are described in the following sections and provides more control over the setup process and enable custom configurations.

## Prerequisites
<a name="cloudshell-prerequisites"></a>

Before using Amazon Keyspaces with AWS CloudShell, ensure you have:
+ An AWS account with access to Amazon Keyspaces and AWS CloudShell
+ Appropriate IAM permissions to use both services
+ Basic familiarity with Cassandra Query Language (CQL)

## Getting started with AWS CloudShell
<a name="getting-started-cloudshell"></a>

To access AWS CloudShell:

1. Sign in to the AWS Management Console

1. Launch AWS CloudShell by choosing the AWS CloudShell icon in the navigation bar at the top of the console, or by navigating to [https://console.aws.amazon.com/cloudshell/](https://console.aws.amazon.com/cloudshell/)

1. Wait for the AWS CloudShell environment to initialize

## Obtaining IAM permissions for AWS CloudShell
<a name="cloudshell-permissions"></a>

Using the access management resources provided by AWS Identity and Access Management, administrators can grant permissions to IAM users so they can access AWS CloudShell and use the environment's features.

The quickest way for an administrator to grant access to users is through an AWS managed policy. An [AWS managed policy](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-vs-inline.html#aws-managed-policies) is a standalone policy that's created and administered by AWS. The following AWS managed policy for CloudShell can be attached to IAM identities:
+ `AWSCloudShellFullAccess`: Grants permission to use AWS CloudShell with full access to all features.

If you want to limit the scope of actions that an IAM user can perform with AWS CloudShell, you can create a custom policy that uses the `AWSCloudShellFullAccess` managed policy as a template. For more information about limiting the actions that are available to users in CloudShell, see [Managing AWS CloudShell access and usage with IAM policies](https://docs.aws.amazon.com/cloudshell/latest/userguide/sec-auth-with-identities.html) in the *AWS CloudShell User Guide*.

**Note**  
Your IAM identity also requires a policy that grants permission to make calls to Amazon Keyspaces.

You can use an AWS managed policy to give your IAM identity access you Amazon Keyspaces, or start with the managed policy as a template and remove the permissions that you don't need. You can also limit access to specific keyspaces and tables to create a custom policy. The following managed policy for Amazon Keyspaces can be attached to IAM identities:
+ [AmazonKeyspacesFullAccess](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonKeyspacesFullAccess.html) – This policy grants permission to use Amazon Keyspaces with full access to all features.

For a detailed explanation of the actions defined in the managed policy, see [AWS managed policies for Amazon Keyspaces](security-iam-awsmanpol.md).

 For more information about how to restrict actions or limit access to specific resources in Amazon Keyspaces, see [How Amazon Keyspaces works with IAM](security_iam_service-with-iam.md).

## Installing the cqlsh client
<a name="installing-cqlsh-client"></a>

AWS CloudShell does not come with `cqlsh` pre-installed. You need to install it to interact with Amazon Keyspaces. You can install the Amazon Keyspaces-specific version of `cqlsh`. For `cqlsh-expansion` installation instructions, see [Using the `cqlsh-expansion` to connect to Amazon Keyspaces](programmatic.cqlsh.md#using_cqlsh).

## Configuring TLS certificates
<a name="configuring-ssl-certificates"></a>

To connect to Amazon Keyspaces using a TLS connection, you need to download the required Amazon digital certificates. For detailed instructions on downloading and configuring the SSL certificate, see [How to manually configure `cqlsh` connections for TLS](programmatic.cqlsh.md#encrypt_using_tls).

## Connecting to Amazon Keyspaces
<a name="connecting-to-keyspaces"></a>

You can connect to Amazon Keyspaces using either IAM credentials (recommended) or service-specific credentials.

### Connecting with IAM credentials (recommended)
<a name="connecting-iam-credentials"></a>

AWS CloudShell is already authenticated with your IAM credentials. To connect using these credentials, you can use the SigV4 authentication plugin. For detailed instructions on using IAM credentials with `cqlsh`, see [Using the `cqlsh-expansion` to connect to Amazon Keyspaces](programmatic.cqlsh.md#using_cqlsh).

### Connecting with service-specific credentials
<a name="connecting-service-specific-credentials"></a>

If you have created service-specific credentials for Amazon Keyspaces, you can use them to connect. For information about creating and using service-specific credentials, see [Create service-specific credentials for programmatic access to Amazon Keyspaces](programmatic.credentials.ssc.md).

## Using CQLSH with Amazon Keyspaces
<a name="using-cqlsh-keyspaces"></a>

When connected, you can use standard CQL commands to interact with your keyspaces and tables. For detailed information about supported CQL commands and operations, see [Using the `cqlsh-expansion` to connect to Amazon Keyspaces](programmatic.cqlsh.md#using_cqlsh).

## Persisting data in AWS CloudShell
<a name="persisting-data-cloudshell"></a>

AWS CloudShell provides 1 GB of persistent storage in your home directory. This means scripts, certificates, and configuration files you create remain available across sessions. You can create a configuration file for `cqlsh` to simplify connections.

With a configuration file, you can run `cqlsh` without specifying additional parameters. For more information about creating and using `cqlsh` configuration files, see [Using the `cqlsh-expansion` to connect to Amazon Keyspaces](programmatic.cqlsh.md#using_cqlsh).

## Best practices
<a name="best-practices-cloudshell"></a>

When using Amazon Keyspaces with AWS CloudShell, we recommend the following best practices:
+ Create scripts for repetitive tasks and store them in your persistent home directory.
+ Use environment variables for sensitive information rather than hardcoding them.
+ Remember that AWS CloudShell sessions may time out after inactivity.
+ Be mindful of the AWS CloudShell service quotas and limitations.
+ Consider using the AWS CLI for automated operations with Amazon Keyspaces.

## Troubleshooting
<a name="troubleshooting-cloudshell"></a>

If you encounter issues when connecting to Amazon Keyspaces from AWS CloudShell:
+ Verify your IAM permissions include the necessary Amazon Keyspaces actions.
+ Ensure that you are using the correct endpoint for your Region.
+ Check that the SSL certificates are correctly downloaded and referenced.
+ Verify that your service-specific credentials are correct and not expired.
+ If using a cqlshrc file, check its formatting and permissions.

## Example: How to interact with Amazon Keyspaces using AWS CloudShell
<a name="cshell-examples"></a>

After you launch AWS CloudShell from the AWS Management Console, you can immediately start to interact with Amazon Keyspaces using `cqlsh` or the command line interface. If you haven't already installed the `cqlsh-expansion`, see [Using the `cqlsh-expansion` to connect to Amazon Keyspaces](programmatic.cqlsh.md#using_cqlsh) for detailed steps.

**Note**  
When using the `cqlsh-expansion` in AWS CloudShell, you don't need to configure credentials before making calls, because you're already authenticated within the shell.

**Connect to Amazon Keyspaces and create a new keyspace. Then read from a system table to confirm that the keyspace was created using AWS CloudShell**

1. From the AWS Management Console, you can launch CloudShell by choosing the following options available on the navigation bar:
   +  Choose the CloudShell icon. 
   + Start typing `cloudshell` in the search box and then choose the CloudShell option.

1. You can establish a connection to Amazon Keyspaces using the following command. Make sure to replace `cassandra.us-east-1.amazonaws.com` with the correct endpoint for your Region.

   ```
   cqlsh-expansion cassandra.us-east-1.amazonaws.com 9142 --ssl
   ```

   If the connection is successful, you should see output similar to the following example.

   ```
   Connected to Amazon Keyspaces at cassandra.us-east-1.amazonaws.com:9142
   [cqlsh 6.1.0 | Cassandra 3.11.2 | CQL spec 3.4.4 | Native protocol v4]
   Use HELP for help.
   cqlsh current consistency level is ONE.
   cqlsh>
   ```

1. Create a new keyspace with the name `mykeyspace`. You can use the following command to do that.

   ```
   CREATE KEYSPACE mykeyspace WITH REPLICATION = {'class': 'SingleRegionStrategy'};
   ```

1. To confirm that the keyspace was created, you can read from a system table using the following command.

   ```
   SELECT * FROM system_schema_mcs.keyspaces WHERE keyspace_name = 'mykeyspace';
   ```

   If the call is successful, the command line displays a response from the service similar to the following output:

   ```
    keyspace_name  | durable_writes | replication
   ----------------+----------------+-------------------------------------------------------------------------------------
    mykeyspace     |           True | {'class': 'org.apache.cassandra.locator.SimpleStrategy', 'replication_factor': '3'}
   
   (1 rows)
   ```

# Create credentials for programmatic access to Amazon Keyspaces
<a name="programmatic.credentials"></a>

To provide users and applications with credentials for programmatic access to Amazon Keyspaces resources, you can do either of the following:
+ Create service-specific credentials that are similar to the traditional username and password that Cassandra uses for authentication and access management. AWS service-specific credentials are associated with a specific AWS Identity and Access Management (IAM) user and can only be used for the service they were created for. For more information, see [Using IAM with Amazon Keyspaces (for Apache Cassandra)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_keyspaces.html) in the IAM User Guide.
**Warning**  
IAM users have long-term credentials, which presents a security risk. To help mitigate this risk, we recommend that you provide these users with only the permissions they require to perform the task and that you remove these users when they are no longer needed.
+ For enhanced security, we recommend to create IAM identities that are used across all AWS services and use temporary credentials. The Amazon Keyspaces SigV4 authentication plugin for Cassandra client drivers enables you to authenticate calls to Amazon Keyspaces using IAM access keys instead of user name and password. To learn more about how the Amazon Keyspaces SigV4 plugin enables [IAM users, roles, and federated identities](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) to authenticate in Amazon Keyspaces API requests, see [AWS Signature Version 4 process (SigV4)](https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html). 

  You can download the SigV4 plugins from the following locations.
  + Java: [https://github.com/aws/aws-sigv4-auth-cassandra-java-driver-plugin](https://github.com/aws/aws-sigv4-auth-cassandra-java-driver-plugin).
  + Node.js: [https://github.com/aws/aws-sigv4-auth-cassandra-nodejs-driver-plugin](https://github.com/aws/aws-sigv4-auth-cassandra-nodejs-driver-plugin).
  + Python: [https://github.com/aws/aws-sigv4-auth-cassandra-python-driver-plugin](https://github.com/aws/aws-sigv4-auth-cassandra-python-driver-plugin).
  + Go: [https://github.com/aws/aws-sigv4-auth-cassandra-gocql-driver-plugin](https://github.com/aws/aws-sigv4-auth-cassandra-gocql-driver-plugin).

  For code samples that show how to establish connections using the SigV4 authentication plugin, see [Using a Cassandra client driver to access Amazon Keyspaces programmatically](programmatic.drivers.md).

**Topics**
+ [Create service-specific credentials](programmatic.credentials.ssc.md)
+ [Create IAM credentials for AWS authentication](access.credentials.md)

# Create service-specific credentials for programmatic access to Amazon Keyspaces
<a name="programmatic.credentials.ssc"></a>

Service-specific credentials are similar to the traditional username and password that Cassandra uses for authentication and access management. Service-specific credentials enable IAM users to access a specific AWS service. These long-term credentials can't be used to access other AWS services. They are associated with a specific IAM user and can't be used by other IAM users.

**Important**  
Service-specific credentials are long-term credentials associated with a specific IAM user and can only be used for the service they were created for. To give IAM roles or federated identities permissions to access all your AWS resources using temporary credentials, you should use [AWS authentication with the SigV4 authentication plugin for Amazon Keyspaces](access.credentials.md).

Use one of the following procedures to generate service-specific credentials.

------
#### [ Console ]

**Create service-specific credentials using the console**

1. Sign in to the AWS Management Console and open the AWS Identity and Access Management console at [https://console.aws.amazon.com/iam/home](https://console.aws.amazon.com/iam/home).

1. In the navigation pane, choose **Users**, and then choose the user that you created earlier that has Amazon Keyspaces permissions (policy attached). 

1. Choose **Security Credentials**. Under **Credentials for Amazon Keyspaces**, choose **Generate credentials** to generate the service-specific credentials.

   Your service-specific credentials are now available. This is the only time you can download or view the password. You cannot recover it later. However, you can reset your password at any time. Save the user and password in a secure location, because you'll need them later.

------
#### [ CLI ]

**Create service-specific credentials using the AWS CLI**

 Before generating service-specific credentials, you need to download, install, and configure the AWS Command Line Interface (AWS CLI):

1. Download the AWS CLI at [http://aws.amazon.com/cli](https://aws.amazon.com/cli). 
**Note**  
The AWS CLI runs on Windows, macOS, or Linux. 

1. Follow the instructions for [Installing the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/installing.html) and [Configuring the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html) in the *AWS Command Line Interface User Guide*.

1. Using the AWS CLI, run the following command to generate service-specific credentials for the user `alice`, so that she can access Amazon Keyspaces.

   ```
   aws iam create-service-specific-credential \
       --user-name alice \
       --service-name cassandra.amazonaws.com
   ```

The output looks like the following.

```
{
    "ServiceSpecificCredential": {
        "CreateDate": "2019-10-09T16:12:04Z",
        "ServiceName": "cassandra.amazonaws.com",
        "ServiceUserName": "alice-at-111122223333",
        "ServicePassword": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
        "ServiceSpecificCredentialId": "ACCAYFI33SINPGJEBYESF",
        "UserName": "alice",
        "Status": "Active"
    }
}
```

In the output, note the values for `ServiceUserName` and `ServicePassword`. Save these values in a secure location, because you'll need them later.

**Important**  
This is the only time that the `ServicePassword` will be available to you.

------

# Create and configure AWS credentials for Amazon Keyspaces
<a name="access.credentials"></a>

To access Amazon Keyspaces programmatically with the AWS CLI, the AWS SDK, or with Cassandra client drivers and the SigV4 plugin, you need an IAM user with access keys. When you use Amazon Keyspaces programmatically, you provide your AWS access keys so that AWS can verify your identity in programmatic calls. Your access keys consist of an access key ID (for example, AKIAIOSFODNN7EXAMPLE) and a secret access key (for example, wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY). This topic walks you through the required steps in this process. 

Security best practices recommend that you create IAM users with limited permissions and instead associate IAM roles with the permissions needed to perform specific tasks. IAM users can then temporarily assume IAM roles to perform the required tasks. For example, IAM users in your account using the Amazon Keyspaces console can switch to a role to temporarily use the permissions of the role in the console. The users give up their original permissions and take on the permissions assigned to the role. When the users exit the role, their original permissions are restored. The credentials the users use to assume the role are temporary. On the contrary, IAM users have long-term credentials, which presents a security risk if instead of assuming roles they have permissions directly assigned to them. To help mitigate this risk, we recommend that you provide these users with only the permissions they require to perform the task and that you remove these users when they are no longer needed. For more information about roles, see [ Common scenarios for roles: Users, applications, and services](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_common-scenarios.html) in the *IAM User Guide*.

**Topics**
+ [Credentials required by the AWS CLI, the AWS SDK, or the Amazon Keyspaces SigV4 plugin for Cassandra client drivers](SigV4_credentials.md)
+ [Create temporary credentials to connect to Amazon Keyspaces using an IAM role and the SigV4 plugin](temporary.credentials.IAM.md)
+ [Create an IAM user for programmatic access to Amazon Keyspaces in your AWS account](access.credentials.IAM.md)
+ [Create new access keys for an IAM user](create.keypair.md)
+ [Store access keys for programmatic access](aws.credentials.manage.md)

# Credentials required by the AWS CLI, the AWS SDK, or the Amazon Keyspaces SigV4 plugin for Cassandra client drivers
<a name="SigV4_credentials"></a>

The following credentials are required to authenticate the IAM user or role:

`AWS_ACCESS_KEY_ID`  
Specifies an AWS access key associated with an IAM user or role.  
The access key `aws_access_key_id` is required to connect to Amazon Keyspaces programmatically.

`AWS_SECRET_ACCESS_KEY`  
Specifies the secret key associated with the access key. This is essentially the "password" for the access key.  
The `aws_secret_access_key` is required to connect to Amazon Keyspaces programmatically. 

`AWS_SESSION_TOKEN` – Optional  
Specifies the session token value that is required if you are using temporary security credentials that you retrieved directly from AWS Security Token Service operations. For more information, see [Create temporary credentials to connect to Amazon Keyspaces using an IAM role and the SigV4 plugin](temporary.credentials.IAM.md).  
If you are connecting with an IAM user, the `aws_session_token` is not required.

# Create temporary credentials to connect to Amazon Keyspaces using an IAM role and the SigV4 plugin
<a name="temporary.credentials.IAM"></a>

The recommended way to access Amazon Keyspaces programmatically is by using [temporary credentials ](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html) to authenticate with the SigV4 plugin. In many scenarios, you don't need long-term access keys that never expire (as you have with an IAM user). Instead, you can create an IAM role and generate temporary security credentials. Temporary security credentials consist of an access key ID and a secret access key, but they also include a security token that indicates when the credentials expire. To learn more about how to use IAM roles instead of long-term access keys, see [ Switching to an IAM role (AWS API)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-api.html).

To get started with temporary credentials, you first need to create an IAM role.

**Create an IAM role that grants read-only access to Amazon Keyspaces**

1. Sign in to the AWS Management Console and open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

1. In the navigation pane, choose **Roles**, then **Create role**.

1. On the **Create role** page, under **Select type of trusted entity**, choose **AWS service**. Under **Choose a use case**, choose **Amazon EC2**, then choose **Next**.

1. On the **Add permissions** page, under **Permissions policies**, choose **Amazon Keyspaces Read Only Access** from the policy list, then choose **Next**.

1. On the **Name, review, and create** page, enter a name for the role, and review the **Select trusted entities** and **Add permissions** sections. You can also add optional tags for the role on this page. When you are done, select **Create role**. Remember this name because you’ll need it when you launch your Amazon EC2 instance.

To use temporary security credentials in code, you programmatically call an AWS Security Token Service API like `AssumeRole` and extract the resulting credentials and session token from your IAM role that you created in the previous step. You then use those values as credentials for subsequent calls to AWS. The following example shows pseudocode for how to use temporary security credentials:

```
assumeRoleResult = AssumeRole(role-arn);
tempCredentials = new SessionAWSCredentials(
   assumeRoleResult.AccessKeyId, 
   assumeRoleResult.SecretAccessKey, 
   assumeRoleResult.SessionToken);
cassandraRequest = CreateAmazoncassandraClient(tempCredentials);
```

For an example that implements temporary credentials using the Python driver to access Amazon Keyspaces, see [Connect to Amazon Keyspaces using the DataStax Python driver for Apache Cassandra and the SigV4 authentication plugin](using_python_driver.md#python_SigV4).

For details about how to call `AssumeRole`, `GetFederationToken`, and other API operations, see the [AWS Security Token Service API Reference](https://docs.aws.amazon.com/STS/latest/APIReference/). For information on getting the temporary security credentials and session token from the result, see the documentation for the SDK that you're working with. You can find the documentation for all the AWS SDKs on the main [AWS documentation page](http://aws.amazon.com/documentation), in the **SDKs and Toolkits** section.

# Create an IAM user for programmatic access to Amazon Keyspaces in your AWS account
<a name="access.credentials.IAM"></a>

To obtain credentials for programmatic access to Amazon Keyspaces with the AWS CLI, the AWS SDK, or the SigV4 plugin, you need to first create an IAM user or role. The process of creating a IAM user and configuring that IAM user to have programmatic access to Amazon Keyspaces is shown in the following steps:

1. Create the user in the AWS Management Console, the AWS CLI, Tools for Windows PowerShell, or using an AWS API operation. If you create the user in the AWS Management Console, then the credentials are created automatically. 

1. If you create the user programmatically, then you must create an access key (access key ID and a secret access key) for that user in an additional step.

1. Give the user permissions to access Amazon Keyspaces. 

For information about the permissions that you need in order to create an IAM user, see [Permissions required to access IAM resources](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_permissions-required.html). 

------
#### [ Console ]

**Create an IAM user with programmatic access (console)**

1. Sign in to the AWS Management Console and open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

1. In the navigation pane, choose **Users** and then choose **Add users**.

1. Type the user name for the new user. This is the sign-in name for AWS. 
**Note**  
User names can be a combination of up to 64 letters, digits, and these characters: plus (\$1), equal (=), comma (,), period (.), at sign (@), underscore (\$1), and hyphen (-). Names must be unique within an account. They are not distinguished by case. For example, you cannot create two users named *TESTUSER* and *testuser*.

1. Select **Access key - Programmatic access** to create an access key for the new user. You can view or download the access key when you get to the **Final** page.

   Choose **Next: Permissions**.

1. On the **Set permissions** page, choose **Attach existing policies directly** to assign permissions to the new user.

   This option displays the list of AWS managed and customer managed policies available in your account. You can enter `keyspaces` into the search field to display only the policies that are related to Amazon Keyspaces.

   For Amazon Keyspaces, the available managed policies are `AmazonKeyspacesFullAccess` and `AmazonKeyspacesReadOnlyAccess`. For more information about each policy, see [AWS managed policies for Amazon Keyspaces](security-iam-awsmanpol.md). 

   For testing purposes and to follow the connection tutorials, select the `AmazonKeyspacesReadOnlyAccess` policy for the new IAM user. **Note:** As a best practice, we recommend that you follow the principle of least privilege and create custom policies that limit access to specific resources and only allow the required actions. For more information about IAM policies and to view example policies for Amazon Keyspaces, see [Amazon Keyspaces identity-based policies](security_iam_service-with-iam.md#security_iam_service-with-iam-id-based-policies). After you have created custom permission policies, attach your policies to roles and then let users assume the appropriate roles temporarily.

   Choose **Next: Tags**.

1. On the **Add tags (optional)** page you can add tags for the user, or choose **Next: Review**. 

1. On the **Review** page you can see all of the choices you made up to this point. When you're ready to proceed, choose **Create user**.

1. To view the user's access keys (access key IDs and secret access keys), choose **Show** next to the password and access key. To save the access keys, choose **Download .csv** and then save the file to a safe location. 
**Important**  
This is your only opportunity to view or download the secret access keys, and you need this information before they can use the SigV4 plugin. Save the user's new access key ID and secret access key in a safe and secure place. You will not have access to the secret keys again after this step.

------
#### [ CLI ]

**Create an IAM user with programmatic access (AWS CLI)**

1. Create a user with the following AWS CLI code.
   + [https://docs.aws.amazon.com/cli/latest/reference/iam/create-user.html](https://docs.aws.amazon.com/cli/latest/reference/iam/create-user.html)

1. Give the user programmatic access. This requires access keys, that can be generated in the following ways. 
   + AWS CLI: [https://docs.aws.amazon.com/cli/latest/reference/iam/create-access-key.html](https://docs.aws.amazon.com/cli/latest/reference/iam/create-access-key.html)
   + Tools for Windows PowerShell: [https://docs.aws.amazon.com/powershell/latest/reference/items/New-IAMAccessKey.html](https://docs.aws.amazon.com/powershell/latest/reference/items/New-IAMAccessKey.html)
   + IAM API: [https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateAccessKey.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateAccessKey.html)
**Important**  
This is your only opportunity to view or download the secret access keys, and you need this information before they can use the SigV4 plugin. Save the user's new access key ID and secret access key in a safe and secure place. You will not have access to the secret keys again after this step.

1. Attach the `AmazonKeyspacesReadOnlyAccess` policy to the user that defines the user's permissions. **Note:** As a best practice, we recommend that you manage user permissions by adding the user to a group and attaching a policy to the group instead of attaching directly to a user.
   + AWS CLI: [https://docs.aws.amazon.com/cli/latest/reference/iam/attach-user-policy.html](https://docs.aws.amazon.com/cli/latest/reference/iam/attach-user-policy.html)

------

# Create new access keys for an IAM user
<a name="create.keypair"></a>

If you already have an IAM user, you can create new access keys at any time. For more information about key management, for example how to update access keys, see [Managing access keys for IAM users](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html). 

**To create access keys for an IAM user (console)**

1. Sign in to the AWS Management Console and open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

1. In the navigation pane, choose **Users**.

1. Choose the name of the user whose access keys you want to create.

1. On the **Summary** page of the user, choose the **Security credentials** tab.

1. In the **Access keys** section under **Access key best practices & alternatives**, choose the use case **Other**. Click **Next**, enter optional information as needed, and choose **Create access key**.

   To view the new access key pair, choose **Show**. Your credentials will look something like this:
   + Access key ID: AKIAIOSFODNN7EXAMPLE
   + Secret access key: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
**Note**  
You will not have access to the secret access key again after this dialog box closes.

   Consider the following best practices for the key pair that you've created.
   + Never store your access key in plain text, in a code repository, or in code.
   + Disable or delete access keys when no longer needed.
   + Enable least-privilege permissions.
   + Rotate access keys regularly.

1. To download the key pair, choose **Download .csv file**. Store the keys in a secure location.

1. After you download the .csv file, choose **Close**.

When you create an access key, the key pair is active by default, and you can use the pair right away.

# Store access keys for programmatic access
<a name="aws.credentials.manage"></a>

As a best practice, we recommend that you don't embed access keys directly into code. The AWS SDKs and the AWS Command Line Tools enable you to put access keys in known locations so that you do not have to keep them in code. Put access keys in one of the following locations:
+ **Environment variables **– On a multitenant system, choose user environment variables, not system environment variables.
+ **CLI credentials file **– The `credentials` and `config` file are updated when you run the command `aws configure`. The `credentials` file is located at `~/.aws/credentials` on Linux, macOS, or Unix, or at `C:\Users\USERNAME\.aws\credentials` on Windows. This file can contain the credential details for the `default` profile and any named profiles.
+ **CLI configuration file **– The `credentials` and `config` file are updated when you run the command `aws configure`. The `config` file is located at `~/.aws/config` on Linux, macOS, or Unix, or at `C:\Users\USERNAME\.aws\config` on Windows. This file contains the configuration settings for the default profile and any named profiles.

Storing access keys as environment variables is a prerequisite for the [Step-by-step tutorial to connect to Amazon Keyspaces using the 4.x DataStax Java driver for Apache Cassandra and the SigV4 authentication plugin](using_java_driver.md#java_tutorial.SigV4). Note that this includes the default AWS Region. The client searches for credentials using the default credentials provider chain, and access keys stored as environment variables take precedent over all other locations, for example configuration files. For more information, see [Configuration settings and precedence](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-quickstart.html#cli-configure-quickstart-precedence).

The following examples show how you can configure environment variables for the default user.

------
#### [ Linux, macOS, or Unix ]

```
$ export AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE
$ export AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
$ export AWS_SESSION_TOKEN=AQoDYXdzEJr...<remainder of security token>
$ export AWS_DEFAULT_REGION=us-east-1
```

Setting the environment variable changes the value used until the end of your shell session, or until you set the variable to a different value. You can make the variables persistent across future sessions by setting them in your shell's startup script.

------
#### [ Windows Command Prompt ]

```
C:\> setx AWS_ACCESS_KEY_ID AKIAIOSFODNN7EXAMPLE
C:\> setx AWS_SECRET_ACCESS_KEY wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
C:\> setx AWS_SESSION_TOKEN AQoDYXdzEJr...<remainder of security token>
C:\> setx AWS_DEFAULT_REGION us-east-1
```

Using `[set](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/set_1)` to set an environment variable changes the value used until the end of the current command prompt session, or until you set the variable to a different value. Using [https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/setx](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/setx) to set an environment variable changes the value used in both the current command prompt session and all command prompt sessions that you create after running the command. It does ***not*** affect other command shells that are already running at the time you run the command.

------
#### [ PowerShell ]

```
PS C:\> $Env:AWS_ACCESS_KEY_ID="AKIAIOSFODNN7EXAMPLE"
PS C:\> $Env:AWS_SECRET_ACCESS_KEY="wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
PS C:\> $Env:AWS_SESSION_TOKEN="AQoDYXdzEJr...<remainder of security token>"
PS C:\> $Env:AWS_DEFAULT_REGION="us-east-1"
```

If you set an environment variable at the PowerShell prompt as shown in the previous examples, it saves the value for only the duration of the current session. To make the environment variable setting persistent across all PowerShell and Command Prompt sessions, store it by using the **System** application in **Control Panel**. Alternatively, you can set the variable for all future PowerShell sessions by adding it to your PowerShell profile. See the [PowerShell documentation](https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_environment_variables) for more information about storing environment variables or persisting them across sessions.

------

# Service endpoints for Amazon Keyspaces
<a name="programmatic.endpoints"></a>

**Topics**
+ [Ports and protocols](#ports)
+ [Global endpoints](#global_endpoints)
+ [AWS GovCloud (US) Region FIPS endpoints](#fips_endpoints)
+ [China Regions endpoints](#china_endpoints)
+ [Streams endpoints](#streams_endpoints)
+ [Connecting to dual-stack endpoints](dualstack_endpoints.md)

## Ports and protocols
<a name="ports"></a>

You can access Amazon Keyspaces programmatically by running a `cqlsh` client, with an Apache 2.0 licensed Cassandra driver, or by using the AWS CLI and the AWS SDK. 

The following table shows the ports and protocols for the different access mechanisms.


| Programmatic Access | Port | Protocol | 
| --- | --- | --- | 
| CQLSH | 9142 | TLS | 
| Cassandra Driver | 9142 | TLS | 
| AWS CLI | 443 | HTTPS | 
| AWS SDK | 443 | HTTPS | 

 For TLS connections, Amazon Keyspaces uses certificates issued under Amazon Trust Services (Amazon Root CAs 1–4) to authenticate against the server. For more information, see [How to manually configure `cqlsh` connections for TLS](programmatic.cqlsh.md#encrypt_using_tls) or the [Before you begin](using_java_driver.md#using_java_driver.BeforeYouBegin) section of your driver in the [Using a Cassandra client driver to access Amazon Keyspaces programmatically](programmatic.drivers.md) chapter.

## Global endpoints
<a name="global_endpoints"></a>

 Amazon Keyspaces supports both IPv4 and IPv6 public endpoints. You can choose between IPv4 endpoints and dual-stack endpoints. The endpoints use the following naming convention, where you can replace *us-east-1* with another available AWS Region from the table.
+ **IPv4 endpoints** – `cassandra.us-east-1.amazonaws.com`
+ **Dual-stack endpoints** – `cassandra.us-east-1.api.aws`

For more information about dual-stack endpoints and how to configure connections, see [Connecting to dual-stack endpoints](dualstack_endpoints.md).

Amazon Keyspaces is available in the following Regions. 

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/keyspaces/latest/devguide/programmatic.endpoints.html)

## AWS GovCloud (US) Region FIPS endpoints
<a name="fips_endpoints"></a>

Available FIPS endpoints in the AWS GovCloud (US) Region. Amazon Keyspaces supports both IPv4 and IPv6 FIPS endpoints. You can choose between IPv4 endpoints and dual-stack endpoints. For more information, see [Amazon Keyspaces in the *AWS GovCloud (US) User Guide*](https://docs.aws.amazon.com/govcloud-us/latest/UserGuide/govcloud-keyspaces.html).

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/keyspaces/latest/devguide/programmatic.endpoints.html)

## China Regions endpoints
<a name="china_endpoints"></a>

Amazon Keyspaces supports IPv4 endpoints in the AWS China Regions. 

To access these endpoints, you have to sign up for a separate set of account credentials unique to the China Regions. For more information, see [China Signup, Accounts, and Credentials](https://docs.amazonaws.cn/en_us/aws/latest/userguide/accounts-and-credentials.html). 

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/keyspaces/latest/devguide/programmatic.endpoints.html)

## Streams endpoints
<a name="streams_endpoints"></a>

Amazon Keyspaces CDC streams is available in the following AWS Regions. This table shows the available dual-stack service endpoint for each Region. For more information about Amazon Keyspaces CDC streams, see [How to access CDC stream endpoints in Amazon Keyspaces](CDC_access-endpoints.md).

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/keyspaces/latest/devguide/programmatic.endpoints.html)

# Connecting to dual-stack endpoints
<a name="dualstack_endpoints"></a>

Amazon Keyspaces global endpoints are dual-stack endpoints that accept IPv4 and IPv6 requests. 

When connecting to Amazon Keyspaces using IPv6, the service automatically adapts system table responses to match your connection protocol. This ensures that your applications receive consistent network address information matching their connection type. This provides accurate network topology information to the client while maintaining backward compatibility for existing CQL applications.

Amazon Keyspaces detects the network protocol (IPv4 or IPv6) used by your client connection automatically and adjusts the system table responses accordingly. This detection happens transparently during the initial connection handshake, requiring no additional configuration from the client application.

Amazon Keyspaces returns IP addresses based on your connection protocol. For example, a request from an IPv4 network returns the following response.

```
SELECT * FROM system.peers;
-- Returns IPv4 addresses in peer column
-- Example: 172.31.1.1, 172.31.1.2, etc.
```

A connection from an IPv6 network to a dual-stack endpoint, for example `cassandra.us-east-1.api.aws`, returns the following response.

```
SELECT * FROM system.peers;
-- Returns IPv6 addresses in peer column
-- Example: 2001:db8::1, 2001:db8::2, etc.
```

For more information about IPv6 support in Amazon Keyspaces, see [IPv6 support in Amazon Keyspaces](ipv6-support.md).

# IPv6 support in Amazon Keyspaces
<a name="ipv6-support"></a>

IPv6 support in Amazon Keyspaces allows applications to establish connections using Internet Protocol version 6, the next-generation internet protocol that provides a vastly expanded address space compared to IPv4. The implementation uses dual-stack endpoints that support both IPv4 and IPv6 simultaneously, ensuring backward compatibility while enabling future-ready connectivity. For a list of endpoints, see [Global endpoints](programmatic.endpoints.md#global_endpoints).

Amazon Keyspaces implements IPv6 support through a dual-stack architecture that maintains complete backward compatibility while enabling IPv6 connectivity.

## DNS resolution in Amazon Keyspaces
<a name="dns-resolution"></a>

When applications connect to dual-stack endpoints, the DNS resolution process returns both address types:

A Records (IPv4)  
Traditional IPv4 addresses for backward compatibility

AAAA Records (IPv6)  
New IPv6 addresses for modern connectivity

The client's operating system and network stack automatically select the most appropriate protocol based on local configuration, network availability, and system preferences.

The Cassandra Query Language (CQL) protocol seamlessly supports IPv6 connectivity without requiring application code changes.

Automatic protocol selection  
+ Applications specify the dual-stack endpoint
+ Network stack chooses IPv4 or IPv6 based on availability
+ No code modifications required for existing CQL applications

Driver compatibility  
+ All major CQL drivers support IPv6 transparently
+ DataStax drivers handle IPv6 addresses natively
+ Open-source drivers work without modification

Connection consistency  
+ System tables reflect the connection protocol used
+ IPv6 connections show IPv6 addresses in `system.peers`
+ IPv4 connections continue showing IPv4 addresses

# Using `cqlsh` to connect to Amazon Keyspaces
<a name="programmatic.cqlsh"></a>

To connect to Amazon Keyspaces using `cqlsh`, you can use the `cqlsh-expansion`. This is a toolkit that contains common Apache Cassandra tooling like `cqlsh` and helpers that are preconfigured for Amazon Keyspaces while maintaining full compatibility with Apache Cassandra. The `cqlsh-expansion` integrates the SigV4 authentication plugin and allows you to connect using IAM access keys instead of user name and password. You only need to install the `cqlsh` scripts to make a connection and not the full Apache Cassandra distribution, because Amazon Keyspaces is serverless. This lightweight install package includes the `cqlsh-expansion` and the classic `cqlsh` scripts that you can install on any platform that supports Python.

**Note**  
`Murmur3Partitioner` is the recommended partitioner for Amazon Keyspaces and the `cqlsh-expansion`. The `cqlsh-expansion` doesn't support the Amazon Keyspaces `DefaultPartitioner`. For more information, see [Working with partitioners in Amazon Keyspaces](working-with-partitioners.md).

For general information about `cqlsh`, see [`cqlsh`: the CQL shell](https://cassandra.apache.org/doc/latest/cassandra/managing/tools/cqlsh.html).

**Topics**
+ [Using the `cqlsh-expansion` to connect to Amazon Keyspaces](#using_cqlsh)
+ [How to manually configure `cqlsh` connections for TLS](#encrypt_using_tls)

## Using the `cqlsh-expansion` to connect to Amazon Keyspaces
<a name="using_cqlsh"></a>

**Installing and configuring the `cqlsh-expansion`**

1. To install the `cqlsh-expansion` Python package, you can run a `pip` command. This installs the `cqlsh-expansion` scripts on your machine using a *pip install* along with a file containing a list of dependencies. The `--user flag` tells `pip` to use the Python user install directory for your platform. On a Unix based system, that should be the `~/.local/` directory.

   You need Python 3 to install the `cqlsh-expansion`, to find out your Python version, use `Python --version`. To install, you can run the following command.

   ```
   python3 -m pip install --user cqlsh-expansion
   ```

   The output should look similar to this.

   ```
   Collecting cqlsh-expansion
     Downloading cqlsh_expansion-0.9.6-py3-none-any.whl (153 kB)
        ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 153.7/153.7 KB 3.3 MB/s eta 0:00:00
   Collecting cassandra-driver
     Downloading cassandra_driver-3.28.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (19.1 MB)
        ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 19.1/19.1 MB 44.5 MB/s eta 0:00:00
   Requirement already satisfied: six>=1.12.0 in /usr/lib/python3/dist-packages (from cqlsh-expansion) (1.16.0)
   Collecting boto3
     Downloading boto3-1.29.2-py3-none-any.whl (135 kB)
        ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 135.8/135.8 KB 17.2 MB/s eta 0:00:00
   Collecting cassandra-sigv4>=4.0.2
     Downloading cassandra_sigv4-4.0.2-py2.py3-none-any.whl (9.8 kB)
   Collecting botocore<1.33.0,>=1.32.2
     Downloading botocore-1.32.2-py3-none-any.whl (11.4 MB)
        ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 11.4/11.4 MB 60.9 MB/s eta 0:00:00
   Collecting s3transfer<0.8.0,>=0.7.0
     Downloading s3transfer-0.7.0-py3-none-any.whl (79 kB)
        ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 79.8/79.8 KB 13.1 MB/s eta 0:00:00
   Collecting jmespath<2.0.0,>=0.7.1
     Downloading jmespath-1.0.1-py3-none-any.whl (20 kB)
   Collecting geomet<0.3,>=0.1
     Downloading geomet-0.2.1.post1-py3-none-any.whl (18 kB)
   Collecting python-dateutil<3.0.0,>=2.1
     Downloading python_dateutil-2.8.2-py2.py3-none-any.whl (247 kB)
        ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 247.7/247.7 KB 33.1 MB/s eta 0:00:00
   Requirement already satisfied: urllib3<2.1,>=1.25.4 in /usr/lib/python3/dist-packages (from botocore<1.33.0,>=1.32.2->boto3->cqlsh-expansion) (1.26.5)
   Requirement already satisfied: click in /usr/lib/python3/dist-packages (from geomet<0.3,>=0.1->cassandra-driver->cqlsh-expansion) (8.0.3)
   Installing collected packages: python-dateutil, jmespath, geomet, cassandra-driver, botocore, s3transfer, boto3, cassandra-sigv4, cqlsh-expansion
     WARNING: The script geomet is installed in '/home/ubuntu/.local/bin' which is not on PATH.
     Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
     WARNING: The scripts cqlsh, cqlsh-expansion and cqlsh-expansion.init are installed in '/home/ubuntu/.local/bin' which is not on PATH.
     Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
   Successfully installed boto3-1.29.2 botocore-1.32.2 cassandra-driver-3.28.0 cassandra-sigv4-4.0.2 cqlsh-expansion-0.9.6 geomet-0.2.1.post1 jmespath-1.0.1 python-dateutil-2.8.2 s3transfer-0.7.0
   ```

   If the install directory is not in the `PATH`, you need to add it following the instructions of your operating system. Below is one example for Ubuntu Linux.

   ```
   export PATH="$PATH:/home/ubuntu/.local/bin"
   ```

   To confirm that the package is installed, you can run the following command.

   ```
   cqlsh-expansion --version
   ```

   The output should look like this.

   ```
   cqlsh 6.1.0
   ```

1. To configure the `cqlsh-expansion`, you can run a post-install script to automatically complete the following steps:

   1. Create the `.cassandra` directory in the user home directory if it doesn't already exist.

   1. Copy a preconfigured `cqlshrc` configuration file into the `.cassandra` directory.

   1. Copy the combined certificate file into the `.cassandra` directory. Amazon Keyspaces uses this certificate to configure the secure connection with Transport Layer Security (TLS). Encryption in transit provides an additional layer of data protection by encrypting your data as it travels to and from Amazon Keyspaces. For more information about certificates, see [How to manually configure `cqlsh` connections for TLS](#encrypt_using_tls).

   To review the script first, you can access it in the Github repo at [https://github.com/aws-samples/amazon-keyspaces-toolkit/blob/master/cqlsh-expansion/cqlsh_expansion/post_install.py](https://github.com/aws-samples/amazon-keyspaces-toolkit/blob/master/cqlsh-expansion/cqlsh_expansion/post_install.py).

   To use the script, you can run the following command. 

   ```
   cqlsh-expansion.init
   ```
**Note**  
The directory and file created by the post-install script are not removed when you uninstall the `cqlsh-expansion` using `pip uninstall`, and have to be deleted manually.

**Connecting to Amazon Keyspaces using the `cqlsh-expansion`**

1. Configure your AWS Region and add it as a user environment variable.

   To add your default Region as an environment variable on a Unix based system, you can run the following command. For this example, we use `us-east-1`.

   ```
   export AWS_DEFAULT_REGION=us-east-1
   ```

   For more information about how to set environment variables, including for other platforms, see [How to set environment variables](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-envvars.html#envvars-set).

1. Find your service endpoint.

   Choose the appropriate service endpoint for your Region. To review the available endpoints for Amazon Keyspaces, see [Service endpoints for Amazon Keyspaces](programmatic.endpoints.md). For this example, we use the endpoint `cassandra.us-east-1.amazonaws.com`.

1. Configure the authentication method.

   Connecting with IAM access keys (IAM users, roles, and federated identities) is the recommended method for enhanced security. 

   Before you can connect with IAM access keys, you need to complete the following steps:

   1. Create an IAM user, or follow the best practice and create an IAM role that IAM users can assume. For more information on how to create IAM access keys, see [Create and configure AWS credentials for Amazon Keyspaces](access.credentials.md).

   1. Create an IAM policy that grants the role (or IAM user) at least read-only access to Amazon Keyspaces. For more information about the permissions required for the IAM user or role to connect to Amazon Keyspaces, see [Accessing Amazon Keyspaces tables](security_iam_id-based-policy-examples.md#security_iam_id-based-policy-examples-access-one-table).

   1. Add the access keys of the IAM user to the user's environment variables as shown in the following example.

      ```
      export AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE
      export AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
      ```

      For more information about how to set environment variables, including for other platforms, see [How to set environment variables](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-envvars.html#envvars-set).
**Note**  
If you're connecting from an Amazon EC2 instance, you also need to configure an outbound rule in the security group that allows traffic from the instance to Amazon Keyspaces. For more information about how to view and edit EC2 outbound rules, see [Add rules to a security group in the Amazon EC2 User Guide](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/working-with-security-groups.html#adding-security-group-rule).

1. Connect to Amazon Keyspaces using the `cqlsh-expansion` and SigV4 authentication.

   To connect to Amazon Keyspaces with the `cqlsh-expansion`, you can use the following command. Make sure to replace the service endpoint with the correct endpoint for your Region.

   ```
   cqlsh-expansion cassandra.us-east-1.amazonaws.com 9142 --ssl
   ```

   If the connection is successful, you should see output similar to the following example.

   ```
   Connected to Amazon Keyspaces at cassandra.us-east-1.amazonaws.com:9142
   [cqlsh 6.1.0 | Cassandra 3.11.2 | CQL spec 3.4.4 | Native protocol v4]
   Use HELP for help.
   cqlsh current consistency level is ONE.
   cqlsh>
   ```

   If you encounter a connection error, see [I can't connect to Amazon Keyspaces with cqlsh](troubleshooting.connecting.md#troubleshooting.connection.cqlsh) for troubleshooting information.
   + Connect to Amazon Keyspaces with service-specific credentials.

     To connect with the traditional username and password combination that Cassandra uses for authentication, you must first create service-specific credentials for Amazon Keyspaces as described in [Create service-specific credentials for programmatic access to Amazon Keyspaces](programmatic.credentials.ssc.md). You also have to give that user permissions to access Amazon Keyspaces, for more information see [Accessing Amazon Keyspaces tables](security_iam_id-based-policy-examples.md#security_iam_id-based-policy-examples-access-one-table). 

     After you have created service-specific credentials and permissions for the user, you must update the `cqlshrc` file, typically found in the user directory path `~/.cassandra/`. In the `cqlshrc` file, go to the Cassandra `[authentication]` section and comment out the SigV4 module and class under `[auth_provider]` using the ";" character as shown in the following example. 

     ```
     [auth_provider]
     
     ; module = cassandra_sigv4.auth
     
     ; classname = SigV4AuthProvider
     ```

     After you have updated the `cqlshrc` file, you can connect to Amazon Keyspaces with service-specific credentials using the following command.

     ```
     cqlsh-expansion cassandra.us-east-1.amazonaws.com 9142 -u myUserName -p myPassword --ssl
     ```

**Cleanup**
+ To remove the `cqlsh-expansion` package you can use the `pip uninstall` command.

  ```
  pip3 uninstall cqlsh-expansion
  ```

  The `pip3 uninstall` command doesn't remove the directory and related files created by the post-install script. To remove the folder and files created by the post-install script, you can delete the `.cassandra` directory.

## How to manually configure `cqlsh` connections for TLS
<a name="encrypt_using_tls"></a>

Amazon Keyspaces only accepts secure connections using Transport Layer Security (TLS). You can use the `cqlsh-expansion` utility that automatically downloads the certificates for you and installs a preconfigured `cqlshrc` configuration file. For more information, see [Using the `cqlsh-expansion` to connect to Amazon Keyspaces](#using_cqlsh) on this page. 

If you want to download the certificates and configure the connection manually, you can do so using the following steps. 

1.  Download the following digital certificates and save the files locally or in your home directory.

   1. AmazonRootCA1

   1. AmazonRootCA2

   1. AmazonRootCA3

   1. AmazonRootCA4

   1. Starfield Class 2 Root (optional – for backward compatibility)

   To download the certificates, you can use the following commands.

   ```
   curl -O https://www.amazontrust.com/repository/AmazonRootCA1.pem
   curl -O https://www.amazontrust.com/repository/AmazonRootCA2.pem
   curl -O https://www.amazontrust.com/repository/AmazonRootCA3.pem
   curl -O https://www.amazontrust.com/repository/AmazonRootCA4.pem
   curl -O https://certs.secureserver.net/repository/sf-class2-root.crt
   ```
**Note**  
Amazon Keyspaces previously used TLS certificates anchored to the Starfield Class 2 CA. AWS is migrating all AWS Regions to certificates issued under Amazon Trust Services (Amazon Root CAs 1–4). During this transition, configure clients to trust both Amazon Root CAs 1–4 and the Starfield root to ensure compatibility across all Regions.

1. Combine all downloaded certificates into a single `pem` file with the name *keyspaces-bundle.pem* in our examples. You can do this by running the following command. Take note of the path to the file, you need this later.

   ```
   cat AmazonRootCA1.pem \
    AmazonRootCA2.pem \
    AmazonRootCA3.pem \
    AmazonRootCA4.pem \
    sf-class2-root.crt \
    > keyspaces-bundle.pem
   ```

1. Open the `cqlshrc` configuration file in the Cassandra home directory, for example `${HOME}/.cassandra/cqlshrc` and add the following lines.

   ```
   [connection]
   port = 9142
   factory = cqlshlib.ssl.ssl_transport_factory
   
   [ssl]
   validate = true
   certfile =  path_to_file/keyspaces-bundle.pem
   ```

# Using the AWS CLI to connect to Amazon Keyspaces
<a name="access.cli"></a>

 You can use the AWS Command Line Interface (AWS CLI) to control multiple AWS services from the command line and automate them through scripts. With Amazon Keyspaces you can use the AWS CLI for data definition language (DDL) operations, such as creating a table. In addition, you can use infrastructure as code (IaC) services and tools such as AWS CloudFormation and Terraform.

Before you can use the AWS CLI with Amazon Keyspaces, you must get an access key ID and secret access key. For more information, see [Create and configure AWS credentials for Amazon Keyspaces](access.credentials.md).

For a complete listing of all the commands available for Amazon Keyspaces in the AWS CLI, see the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/keyspaces/index.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/keyspaces/index.html). 

**Topics**
+ [Downloading and Configuring the AWS CLI](#access.cli.installcli)
+ [Using the AWS CLI with Amazon Keyspaces](#access.cli.usingcli)

## Downloading and Configuring the AWS CLI
<a name="access.cli.installcli"></a>

The AWS CLI is available at [https://aws.amazon.com/cli](https://aws.amazon.com/cli). It runs on Windows, macOS, or Linux. After downloading the AWS CLI, follow these steps to install and configure it:

1. Go to the [AWS Command Line Interface User Guide](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)

1. Follow the instructions for [Installing the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html) and [Configuring the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)

## Using the AWS CLI with Amazon Keyspaces
<a name="access.cli.usingcli"></a>

The command line format consists of a Amazon Keyspaces operation name followed by the parameters for that operation. The AWS CLI supports a shorthand syntax for the parameter values, as well as JSON. The following Amazon Keyspaces examples use AWS CLI shorthand syntax. For more information, see [Using shorthand syntax with the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-shorthand.html).

The following command creates a keyspace with the name *catalog*.

```
aws keyspaces create-keyspace --keyspace-name 'catalog'
```

The command returns the resource Amazon Resource Name (ARN) in the output.

```
{
    "resourceArn": "arn:aws:cassandra:us-east-1:111122223333:/keyspace/catalog/"
}
```

To confirm that the keyspace *catalog* exists, you can use the following command.

```
aws keyspaces get-keyspace --keyspace-name 'catalog'
```

The output of the command returns the following values.

```
{
    "keyspaceName": "catalog",
    "resourceArn": "arn:aws:cassandra:us-east-1:111122223333:/keyspace/catalog/"
}
```

The following command creates a table with the name *book\$1awards*. The partition key of the table consists of the columns `year` and `award` and the clustering key consists of the columns `category` and `rank`, both clustering columns use the ascending sort order. (For easier readability, long commands in this section are broken into separate lines.)

```
aws keyspaces create-table --keyspace-name 'catalog' --table-name 'book_awards' 
            --schema-definition 'allColumns=[{name=year,type=int},{name=award,type=text},{name=rank,type=int},
            {name=category,type=text}, {name=author,type=text},{name=book_title,type=text},{name=publisher,type=text}],
            partitionKeys=[{name=year},{name=award}],clusteringKeys=[{name=category,orderBy=ASC},{name=rank,orderBy=ASC}]'
```

This command results in the following output.

```
{
    "resourceArn": "arn:aws:cassandra:us-east-1:111122223333:/keyspace/catalog/table/book_awards"
}
```

To confirm the metadata and properties of the table, you can use the following command.

```
aws keyspaces get-table --keyspace-name 'catalog' --table-name 'book_awards'
```

This command returns the following output.

```
{
    "keyspaceName": "catalog",
    "tableName": "book_awards",
    "resourceArn": "arn:aws:cassandra:us-east-1:111122223333:/keyspace/catalog/table/book_awards",
    "creationTimestamp": 1645564368.628,
    "status": "ACTIVE",
    "schemaDefinition": {
        "allColumns": [
            {
                "name": "year",
                "type": "int"
            },
            {
                "name": "award",
                "type": "text"
            },
            {
                "name": "category",
                "type": "text"
            },
            {
                "name": "rank",
                "type": "int"
            },
            {
                "name": "author",
                "type": "text"
            },
            {
                "name": "book_title",
                "type": "text"
            },
            {
                "name": "publisher",
                "type": "text"
            }
        ],
        "partitionKeys": [
            {
                "name": "year"
            },
            {
                "name": "award"
            }
        ],
        "clusteringKeys": [
            {
                "name": "category",
                "orderBy": "ASC"
            },
            {
                "name": "rank",
                "orderBy": "ASC"
            }
        ],
        "staticColumns": []
    },
    "capacitySpecification": {
        "throughputMode": "PAY_PER_REQUEST",
        "lastUpdateToPayPerRequestTimestamp": 1645564368.628
    },
    "encryptionSpecification": {
        "type": "AWS_OWNED_KMS_KEY"
    },
    "pointInTimeRecovery": {
        "status": "DISABLED"
    },
    "ttl": {
        "status": "ENABLED"
    },
    "defaultTimeToLive": 0,
    "comment": {
        "message": ""
    }
}
```

When creating tables with complex schemas, it can be helpful to load the table's schema definition from a JSON file. The following is an example of this. Download the schema definition example JSON file from [schema\$1definition.zip](samples/schema_definition.zip) and extract `schema_definition.json`, taking note of the path to the file. In this example, the schema definition JSON file is located in the current directory. For different file path options, see [ How to load parameters from a file](https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-parameters-file.html#cli-usage-parameters-file-how).

```
aws keyspaces create-table --keyspace-name 'catalog' 
            --table-name 'book_awards' --schema-definition 'file://schema_definition.json'
```

The following examples show how to create a simple table with the name *myTable* with additional options. Note that the commands are broken down into separate rows to improve readability. This command shows how to create a table and:
+ set the capacity mode of the table
+ enable Point-in-time recovery for the table
+ set the default Time to Live (TTL) value for the table to one year
+ add two tags for the table

```
aws keyspaces create-table --keyspace-name 'catalog' --table-name 'myTable' 
            --schema-definition 'allColumns=[{name=id,type=int},{name=name,type=text},{name=date,type=timestamp}],partitionKeys=[{name=id}]' 
            --capacity-specification 'throughputMode=PROVISIONED,readCapacityUnits=5,writeCapacityUnits=5' 
            --point-in-time-recovery 'status=ENABLED' 
            --default-time-to-live '31536000' 
            --tags 'key=env,value=test' 'key=dpt,value=sec'
```

This example shows how to create a new table that uses a customer managed key for encryption and has TTL enabled to allow you to set expiration dates for columns and rows. To run this sample, you must replace the resource ARN for the customer managed AWS KMS key with your own key and ensure Amazon Keyspaces has access to it.

```
aws keyspaces create-table --keyspace-name 'catalog' --table-name 'myTable' 
            --schema-definition 'allColumns=[{name=id,type=int},{name=name,type=text},{name=date,type=timestamp}],partitionKeys=[{name=id}]' 
            --encryption-specification 'type=CUSTOMER_MANAGED_KMS_KEY,kmsKeyIdentifier=arn:aws:kms:us-east-1:111122223333:key/11111111-2222-3333-4444-555555555555'  
            --ttl 'status=ENABLED'
```

# Using the API to connect to Amazon Keyspaces
<a name="access.api"></a>

 You can use the AWS SDK and the AWS Command Line Interface (AWS CLI) to work interactively with Amazon Keyspaces. You can use the API for data language definition (DDL) operations, such as creating a keyspace or a table. In addition, you can use infrastructure as code (IaC) services and tools such as AWS CloudFormation and Terraform. 

Before you can use the AWS CLI with Amazon Keyspaces, you must get an access key ID and secret access key. For more information, see [Create and configure AWS credentials for Amazon Keyspaces](access.credentials.md).

For a complete listing of all operations available for Amazon Keyspaces in the API, see [https://docs.aws.amazon.com/keyspaces/latest/APIReference/Welcome.html](https://docs.aws.amazon.com/keyspaces/latest/APIReference/Welcome.html).

# Using a Cassandra client driver to access Amazon Keyspaces programmatically
<a name="programmatic.drivers"></a>

You can use many third-party, open-source Cassandra drivers to connect to Amazon Keyspaces. Amazon Keyspaces is compatible with Cassandra drivers that support Apache Cassandra version 3.11.2. These are the drivers and latest versions that we’ve tested and recommend to use with Amazon Keyspaces: 
+ `Java v3.3`
+ `Java v4.17`
+ `Python Cassandra-driver 3.29.1`
+ `Node.js cassandra driver -v 4.7.2`
+ `GO using GOCQL v1.6`
+ `.NET CassandraCSharpDriver -v 3.20.1`

For more information about Cassandra drivers, see [Apache Cassandra Client drivers](https://cassandra.apache.org/doc/stable/cassandra/getting-started/drivers.html). 

**Note**  
To help you get started, you can view and download end-to-end code examples that establish connections to Amazon Keyspaces with popular drivers. See [Amazon Keyspaces examples](https://github.com/aws-samples/amazon-keyspaces-examples) on GitHub.

The tutorials in this chapter include a simple CQL query to confirm that the connection to Amazon Keyspaces has been successfully established. To learn how to work with keyspaces and tables after you connect to an Amazon Keyspaces endpoint, see [CQL language reference for Amazon Keyspaces (for Apache Cassandra)](cql.md). For a step-by-step tutorial that shows how to connect to Amazon Keyspaces from an Amazon VPC endpoint, see [Tutorial: Connect to Amazon Keyspaces using an interface VPC endpoint](vpc-endpoints-tutorial.md). 

**Topics**
+ [Using a Cassandra Java client driver to access Amazon Keyspaces programmatically](using_java_driver.md)
+ [Using a Cassandra Python client driver to access Amazon Keyspaces programmatically](using_python_driver.md)
+ [Using a Cassandra Node.js client driver to access Amazon Keyspaces programmatically](using_nodejs_driver.md)
+ [Using a Cassandra .NET Core client driver to access Amazon Keyspaces programmatically](using_dotnetcore_driver.md)
+ [Using a Cassandra Go client driver to access Amazon Keyspaces programmatically](using_go_driver.md)
+ [Using a Cassandra Perl client driver to access Amazon Keyspaces programmatically](using_perl_driver.md)

# Using a Cassandra Java client driver to access Amazon Keyspaces programmatically
<a name="using_java_driver"></a>

This section shows you how to connect to Amazon Keyspaces by using a Java client driver.

**Note**  
Java 17 and the DataStax Java Driver 4.17 are currently only in Beta support. For more information, see [https://docs.datastax.com/en/developer/java-driver/4.17/upgrade_guide/](https://docs.datastax.com/en/developer/java-driver/4.17/upgrade_guide/).

To provide users and applications with credentials for programmatic access to Amazon Keyspaces resources, you can do either of the following:
+ Create service-specific credentials that are associated with a specific AWS Identity and Access Management (IAM) user.
+ For enhanced security, we recommend to create IAM access keys for IAM identities that are used across all AWS services. The Amazon Keyspaces SigV4 authentication plugin for Cassandra client drivers enables you to authenticate calls to Amazon Keyspaces using IAM access keys instead of user name and password. For more information, see [Create and configure AWS credentials for Amazon Keyspaces](access.credentials.md).

**Note**  
For an example how to use Amazon Keyspaces with Spring Boot, see [https://github.com/aws-samples/amazon-keyspaces-examples/tree/main/java/datastax-v4/spring](https://github.com/aws-samples/amazon-keyspaces-examples/tree/main/java/datastax-v4/spring).

**Topics**
+ [Before you begin](#using_java_driver.BeforeYouBegin)
+ [Step-by-step tutorial to connect to Amazon Keyspaces using the DataStax Java driver for Apache Cassandra using service-specific credentials](#java_tutorial)
+ [Step-by-step tutorial to connect to Amazon Keyspaces using the 4.x DataStax Java driver for Apache Cassandra and the SigV4 authentication plugin](#java_tutorial.SigV4)
+ [Connect to Amazon Keyspaces using the 3.x DataStax Java driver for Apache Cassandra and the SigV4 authentication plugin](#java3x_tutorial.SigV4)

## Before you begin
<a name="using_java_driver.BeforeYouBegin"></a>

To connect to Amazon Keyspaces, you need to complete the following tasks before you can start.

1. Amazon Keyspaces requires the use of Transport Layer Security (TLS) to help secure connections with clients. 

   1.  Download the following digital certificates and save the files locally or in your home directory.

      1. AmazonRootCA1

      1. AmazonRootCA2

      1. AmazonRootCA3

      1. AmazonRootCA4

      1. Starfield Class 2 Root (optional – for backward compatibility)

      To download the certificates, you can use the following commands.

      ```
      curl -O https://www.amazontrust.com/repository/AmazonRootCA1.pem
      curl -O https://www.amazontrust.com/repository/AmazonRootCA2.pem
      curl -O https://www.amazontrust.com/repository/AmazonRootCA3.pem
      curl -O https://www.amazontrust.com/repository/AmazonRootCA4.pem
      curl -O https://certs.secureserver.net/repository/sf-class2-root.crt
      ```
**Note**  
Amazon Keyspaces previously used TLS certificates anchored to the Starfield Class 2 CA. AWS is migrating all AWS Regions to certificates issued under Amazon Trust Services (Amazon Root CAs 1–4). During this transition, configure clients to trust both Amazon Root CAs 1–4 and the Starfield root to ensure compatibility across all Regions.

   1. Convert the digital certificates into trustStore files and add them to the keystore.

      ```
      openssl x509 -outform der -in AmazonRootCA1.pem -out temp_file.der
      keytool -import -alias amazon-root-ca-1 -keystore cassandra_truststore.jks -file temp_file.der
      
      openssl x509 -outform der -in AmazonRootCA2.pem -out temp_file.der
      keytool -import -alias amazon-root-ca-2 -keystore cassandra_truststore.jks -file temp_file.der
      
      openssl x509 -outform der -in AmazonRootCA3.pem -out temp_file.der
      keytool -import -alias amazon-root-ca-3 -keystore cassandra_truststore.jks -file temp_file.der
      
      openssl x509 -outform der -in AmazonRootCA4.pem -out temp_file.der
      keytool -import -alias amazon-root-ca-4 -keystore cassandra_truststore.jks -file temp_file.der
                   
      openssl x509 -outform der -in sf-class2-root.crt -out temp_file.der
      keytool -import -alias cassandra -keystore cassandra_truststore.jks -file temp_file.der
      ```

      In the last step, you need to create a password for the keystore and trust each certificate. The interactive command looks like this.

      ```
      Enter keystore password:  
      Re-enter new password: 
      Owner: CN=Amazon Root CA 1, O=Amazon, C=US
      Issuer: CN=Amazon Root CA 1, O=Amazon, C=US
      Serial number: 66c9fcf99bf8c0a39e2f0788a43e696365bca
      Valid from: Tue May 26 00:00:00 UTC 2015 until: Sun Jan 17 00:00:00 UTC 2038
      Certificate fingerprints:
           SHA1: 8D:A7:F9:65:EC:5E:FC:37:91:0F:1C:6E:59:FD:C1:CC:6A:6E:DE:16
           SHA256: 8E:CD:E6:88:4F:3D:87:B1:12:5B:A3:1A:C3:FC:B1:3D:70:16:DE:7F:57:CC:90:4F:E1:CB:97:C6:AE:98:19:6E
      Signature algorithm name: SHA256withRSA
      Subject Public Key Algorithm: 2048-bit RSA key
      Version: 3
      
      Extensions: 
      
      #1: ObjectId: 2.5.29.19 Criticality=true
      BasicConstraints:[
        CA:true
        PathLen:2147483647
      ]
      
      #2: ObjectId: 2.5.29.15 Criticality=true
      KeyUsage [
        DigitalSignature
        Key_CertSign
        Crl_Sign
      ]
      
      #3: ObjectId: 2.5.29.14 Criticality=false
      SubjectKeyIdentifier [
      KeyIdentifier [
      0000: 84 18 CC 85 34 EC BC 0C   94 94 2E 08 59 9C C7 B2  ....4.......Y...
      0010: 10 4E 0A 08                                        .N..
      ]
      ]
      
      Trust this certificate? [no]:  yes
      Certificate was added to keystore
      Enter keystore password:  
      Owner: CN=Amazon Root CA 2, O=Amazon, C=US
      Issuer: CN=Amazon Root CA 2, O=Amazon, C=US
      Serial number: 66c9fd29635869f0a0fe58678f85b26bb8a37
      Valid from: Tue May 26 00:00:00 UTC 2015 until: Sat May 26 00:00:00 UTC 2040
      Certificate fingerprints:
           SHA1: 5A:8C:EF:45:D7:A6:98:59:76:7A:8C:8B:44:96:B5:78:CF:47:4B:1A
           SHA256: 1B:A5:B2:AA:8C:65:40:1A:82:96:01:18:F8:0B:EC:4F:62:30:4D:83:CE:C4:71:3A:19:C3:9C:01:1E:A4:6D:B4
      Signature algorithm name: SHA384withRSA
      Subject Public Key Algorithm: 4096-bit RSA key
      Version: 3
      
      Extensions: 
      
      #1: ObjectId: 2.5.29.19 Criticality=true
      BasicConstraints:[
        CA:true
        PathLen:2147483647
      ]
      
      #2: ObjectId: 2.5.29.15 Criticality=true
      KeyUsage [
        DigitalSignature
        Key_CertSign
        Crl_Sign
      ]
      
      #3: ObjectId: 2.5.29.14 Criticality=false
      SubjectKeyIdentifier [
      KeyIdentifier [
      0000: B0 0C F0 4C 30 F4 05 58   02 48 FD 33 E5 52 AF 4B  ...L0..X.H.3.R.K
      0010: 84 E3 66 52                                        ..fR
      ]
      ]
      
      Trust this certificate? [no]:  yes
      Certificate was added to keystore
      Enter keystore password:  
      Owner: CN=Amazon Root CA 3, O=Amazon, C=US
      Issuer: CN=Amazon Root CA 3, O=Amazon, C=US
      Serial number: 66c9fd5749736663f3b0b9ad9e89e7603f24a
      Valid from: Tue May 26 00:00:00 UTC 2015 until: Sat May 26 00:00:00 UTC 2040
      Certificate fingerprints:
           SHA1: 0D:44:DD:8C:3C:8C:1A:1A:58:75:64:81:E9:0F:2E:2A:FF:B3:D2:6E
           SHA256: 18:CE:6C:FE:7B:F1:4E:60:B2:E3:47:B8:DF:E8:68:CB:31:D0:2E:BB:3A:DA:27:15:69:F5:03:43:B4:6D:B3:A4
      Signature algorithm name: SHA256withECDSA
      Subject Public Key Algorithm: 256-bit EC (secp256r1) key
      Version: 3
      
      Extensions: 
      
      #1: ObjectId: 2.5.29.19 Criticality=true
      BasicConstraints:[
        CA:true
        PathLen:2147483647
      ]
      
      #2: ObjectId: 2.5.29.15 Criticality=true
      KeyUsage [
        DigitalSignature
        Key_CertSign
        Crl_Sign
      ]
      
      #3: ObjectId: 2.5.29.14 Criticality=false
      SubjectKeyIdentifier [
      KeyIdentifier [
      0000: AB B6 DB D7 06 9E 37 AC   30 86 07 91 70 C7 9C C4  ......7.0...p...
      0010: 19 B1 78 C0                                        ..x.
      ]
      ]
      
      Trust this certificate? [no]:  yes
      Certificate was added to keystore
      Enter keystore password:  
      Owner: CN=Amazon Root CA 4, O=Amazon, C=US
      Issuer: CN=Amazon Root CA 4, O=Amazon, C=US
      Serial number: 66c9fd7c1bb104c2943e5717b7b2cc81ac10e
      Valid from: Tue May 26 00:00:00 UTC 2015 until: Sat May 26 00:00:00 UTC 2040
      Certificate fingerprints:
           SHA1: F6:10:84:07:D6:F8:BB:67:98:0C:C2:E2:44:C2:EB:AE:1C:EF:63:BE
           SHA256: E3:5D:28:41:9E:D0:20:25:CF:A6:90:38:CD:62:39:62:45:8D:A5:C6:95:FB:DE:A3:C2:2B:0B:FB:25:89:70:92
      Signature algorithm name: SHA384withECDSA
      Subject Public Key Algorithm: 384-bit EC (secp384r1) key
      Version: 3
      
      Extensions: 
      
      #1: ObjectId: 2.5.29.19 Criticality=true
      BasicConstraints:[
        CA:true
        PathLen:2147483647
      ]
      
      #2: ObjectId: 2.5.29.15 Criticality=true
      KeyUsage [
        DigitalSignature
        Key_CertSign
        Crl_Sign
      ]
      
      #3: ObjectId: 2.5.29.14 Criticality=false
      SubjectKeyIdentifier [
      KeyIdentifier [
      0000: D3 EC C7 3A 65 6E CC E1   DA 76 9A 56 FB 9C F3 86  ...:en...v.V....
      0010: 6D 57 E5 81                                        mW..
      ]
      ]
      
      Trust this certificate? [no]:  yes
      Certificate was added to keystore
      Enter keystore password:  
      Owner: OU=Starfield Class 2 Certification Authority, O="Starfield Technologies, Inc.", C=US
      Issuer: OU=Starfield Class 2 Certification Authority, O="Starfield Technologies, Inc.", C=US
      Serial number: 0
      Valid from: Tue Jun 29 17:39:16 UTC 2004 until: Thu Jun 29 17:39:16 UTC 2034
      Certificate fingerprints:
           SHA1: AD:7E:1C:28:B0:64:EF:8F:60:03:40:20:14:C3:D0:E3:37:0E:B5:8A
           SHA256: 14:65:FA:20:53:97:B8:76:FA:A6:F0:A9:95:8E:55:90:E4:0F:CC:7F:AA:4F:B7:C2:C8:67:75:21:FB:5F:B6:58
      Signature algorithm name: SHA1withRSA (weak)
      Subject Public Key Algorithm: 2048-bit RSA key
      Version: 3
      
      Extensions: 
      
      #1: ObjectId: 2.5.29.35 Criticality=false
      AuthorityKeyIdentifier [
      KeyIdentifier [
      0000: BF 5F B7 D1 CE DD 1F 86   F4 5B 55 AC DC D7 10 C2  ._.......[U.....
      0010: 0E A9 88 E7                                        ....
      ]
      [OU=Starfield Class 2 Certification Authority, O="Starfield Technologies, Inc.", C=US]
      SerialNumber: [    00]
      ]
      
      #2: ObjectId: 2.5.29.19 Criticality=false
      BasicConstraints:[
        CA:true
        PathLen:2147483647
      ]
      
      #3: ObjectId: 2.5.29.14 Criticality=false
      SubjectKeyIdentifier [
      KeyIdentifier [
      0000: BF 5F B7 D1 CE DD 1F 86   F4 5B 55 AC DC D7 10 C2  ._.......[U.....
      0010: 0E A9 88 E7                                        ....
      ]
      ]
      
      
      Warning:
      The input uses the SHA1withRSA signature algorithm which is considered a security risk. This algorithm will be disabled in a future update.
      
      Trust this certificate? [no]:  yes
      Certificate was added to keystore
      ```

1.  Attach the trustStore file in the JVM arguments: 

   ```
   -Djavax.net.ssl.trustStore=path_to_file/cassandra_truststore.jks 
   -Djavax.net.ssl.trustStorePassword=my_password
   ```

## Step-by-step tutorial to connect to Amazon Keyspaces using the DataStax Java driver for Apache Cassandra using service-specific credentials
<a name="java_tutorial"></a>

The following step-by-step tutorial walks you through connecting to Amazon Keyspaces using a Java driver for Cassandra using service-specific credentials. Specifically, you'll use the 4.0 version of the DataStax Java driver for Apache Cassandra. 

**Topics**
+ [Step 1: Prerequisites](#java_tutorial.prereq)
+ [Step 2: Configure the driver](#java_tutorial.driverconfiguration)
+ [Step 3: Run the sample application](#java_tutorial.application)

### Step 1: Prerequisites
<a name="java_tutorial.prereq"></a>

To follow this tutorial, you need to generate service-specific credentials and add the DataStax Java driver for Apache Cassandra to your Java project.
+ Generate service-specific credentials for your Amazon Keyspaces IAM user by completing the steps in [Create service-specific credentials for programmatic access to Amazon Keyspaces](programmatic.credentials.ssc.md). If you prefer to use IAM access keys for authentication, see [Step-by-step tutorial to connect to Amazon Keyspaces using the 4.x DataStax Java driver for Apache Cassandra and the SigV4 authentication plugin](#java_tutorial.SigV4).
+ Add the DataStax Java driver for Apache Cassandra to your Java project. Ensure that you're using a version of the driver that supports Apache Cassandra 3.11.2. For more information, see the [DataStax Java driver for Apache Cassandra documentation](https://github.com/datastax/java-driver).

### Step 2: Configure the driver
<a name="java_tutorial.driverconfiguration"></a>

You can specify settings for the DataStax Java Cassandra driver by creating a configuration file for your application. This configuration file overrides the default settings and tells the driver to connect to the Amazon Keyspaces service endpoint using port 9142. For a list of available service endpoints, see [Service endpoints for Amazon Keyspaces](programmatic.endpoints.md).

Create a configuration file and save the file in the application's resources folder—for example, `src/main/resources/application.conf`. Open `application.conf` and add the following configuration settings.

1. **Authentication provider** – Create the authentication provider with the `PlainTextAuthProvider` class. *ServiceUserName* and *ServicePassword* should match the user name and password you obtained when you generated the service-specific credentials by following the steps in [Create service-specific credentials for programmatic access to Amazon Keyspaces](programmatic.credentials.ssc.md).
**Note**  
You can use short-term credentials by using the authentication plugin for the DataStax Java driver for Apache Cassandra instead of hardcoding credentials in your driver configuration file. To learn more, follow the instructions for the [Step-by-step tutorial to connect to Amazon Keyspaces using the 4.x DataStax Java driver for Apache Cassandra and the SigV4 authentication plugin](#java_tutorial.SigV4).

1. **Local data center** – Set the value for `local-datacenter` to the Region you're connecting to. For example, if the application is connecting to `cassandra.us-east-2.amazonaws.com`, then set the local data center to `us-east-2`. For all available AWS Regions, see [Service endpoints for Amazon Keyspaces](programmatic.endpoints.md). Set `slow-replica-avoidance = false` to load balance against fewer nodes.

1. **SSL/TLS** – Initialize the SSLEngineFactory by adding a section in the configuration file with a single line that specifies the class with `class = DefaultSslEngineFactory`. Provide the path to the trustStore file and the password that you created previously. Amazon Keyspaces doesn't support `hostname-validation` of peers, so set this option to false.

```
datastax-java-driver {

    basic.contact-points = [ "cassandra.us-east-2.amazonaws.com:9142"]
    advanced.auth-provider{
        class = PlainTextAuthProvider
        username = "ServiceUserName"
        password = "ServicePassword"
    }
    basic.load-balancing-policy {
        local-datacenter = "us-east-2"
        slow-replica-avoidance = false           
    }

    advanced.ssl-engine-factory {
        class = DefaultSslEngineFactory
        truststore-path = "./src/main/resources/cassandra_truststore.jks"
        truststore-password = "my_password"
        hostname-validation = false
      }
}
```

**Note**  
Instead of adding the path to the trustStore in the configuration file, you can also add the trustStore path directly in the application code or you can add the path to the trustStore to your JVM arguments.

### Step 3: Run the sample application
<a name="java_tutorial.application"></a>

This code example shows a simple command line application that creates a connection pool to Amazon Keyspaces by using the configuration file we created earlier. It confirms that the connection is established by running a simple query.

```
package <your package>;
// add the following imports to your project
import com.datastax.oss.driver.api.core.CqlSession;
import com.datastax.oss.driver.api.core.config.DriverConfigLoader;
import com.datastax.oss.driver.api.core.cql.ResultSet;
import com.datastax.oss.driver.api.core.cql.Row;

public class App 
{
    
    public static void main( String[] args )
    {
        //Use DriverConfigLoader to load your configuration file
        DriverConfigLoader loader = DriverConfigLoader.fromClasspath("application.conf");
        try (CqlSession session = CqlSession.builder()
                .withConfigLoader(loader)
                .build()) {

            ResultSet rs = session.execute("select * from system_schema.keyspaces");
            Row row = rs.one();
            System.out.println(row.getString("keyspace_name"));
        }
    }
}
```

**Note**  
Use a `try` block to establish the connection to ensure that it's always closed. If you don't use a `try` block, remember to close your connection to avoid leaking resources.

## Step-by-step tutorial to connect to Amazon Keyspaces using the 4.x DataStax Java driver for Apache Cassandra and the SigV4 authentication plugin
<a name="java_tutorial.SigV4"></a>

The following section describes how to use the SigV4 authentication plugin for the open-source 4.x DataStax Java driver for Apache Cassandra to access Amazon Keyspaces (for Apache Cassandra). The plugin is available from the [GitHub repository](https://github.com/aws/aws-sigv4-auth-cassandra-java-driver-plugin).

The SigV4 authentication plugin allows you to use IAM credentials for users or roles when connecting to Amazon Keyspaces. Instead of requiring a user name and password, this plugin signs API requests using access keys. For more information, see [Create and configure AWS credentials for Amazon Keyspaces](access.credentials.md). 

### Step 1: Prerequisites
<a name="java_tutorial.SigV4.1"></a>

To follow this tutorial, you need to complete the following tasks.
+ If you haven't already done so, create credentials for your IAM user or role following the steps at [Create and configure AWS credentials for Amazon Keyspaces](access.credentials.md). This tutorial assumes that the access keys are stored as environment variables. For more information, see [Store access keys for programmatic access](aws.credentials.manage.md).
+ Add the DataStax Java driver for Apache Cassandra to your Java project. Ensure that you're using a version of the driver that supports Apache Cassandra 3.11.2. For more information, see the [DataStax Java Driver for Apache Cassandra documentation](https://github.com/datastax/java-driver).
+ Add the authentication plugin to your application. The authentication plugin supports version 4.x of the DataStax Java driver for Apache Cassandra. If you’re using Apache Maven, or a build system that can use Maven dependencies, add the following dependencies to your `pom.xml` file.
**Important**  
Replace the version of the plugin with the latest version as shown at [GitHub repository](https://github.com/aws/aws-sigv4-auth-cassandra-java-driver-plugin#add-the-authentication-plugin-to-the-application).

  ```
  <dependency>
          <groupId>software.aws.mcs</groupId>
          <artifactId>aws-sigv4-auth-cassandra-java-driver-plugin</artifactId>
          <version>4.0.9</version>
  </dependency>
  ```

### Step 2: Configure the driver
<a name="java_tutorial.SigV4.2"></a>

You can specify settings for the DataStax Java Cassandra driver by creating a configuration file for your application. This configuration file overrides the default settings and tells the driver to connect to the Amazon Keyspaces service endpoint using port 9142. For a list of available service endpoints, see [Service endpoints for Amazon Keyspaces](programmatic.endpoints.md).

Create a configuration file and save the file in the application's resources folder—for example, `src/main/resources/application.conf`. Open `application.conf` and add the following configuration settings.

1. **Authentication provider** – Set the `advanced.auth-provider.class` to a new instance of `software.aws.mcs.auth.SigV4AuthProvider`. The SigV4AuthProvider is the authentication handler provided by the plugin for performing SigV4 authentication. 

1. **Local data center** – Set the value for `local-datacenter` to the Region you're connecting to. For example, if the application is connecting to `cassandra.us-east-2.amazonaws.com`, then set the local data center to `us-east-2`. For all available AWS Regions, see [Service endpoints for Amazon Keyspaces](programmatic.endpoints.md). Set `slow-replica-avoidance = false` to load balance against all available nodes.

1. **Idempotence** – Set the default `idempotence` for the application to `true` to configure the driver to always retry failed read/write/prepare/execute requests. This is a best practice for distributed applications that helps to handle transient failures by retrying failed requests.

1. **SSL/TLS** – Initialize the SSLEngineFactory by adding a section in the configuration file with a single line that specifies the class with `class = DefaultSslEngineFactory`. Provide the path to the trustStore file and the password that you created previously. Amazon Keyspaces doesn't support `hostname-validation` of peers, so set this option to false.

1. **Connections** – Create at least 3 local connections per endpoint by setting `local.size = 3`. This is a best practice that helps your application to handle overhead and traffic bursts. For more information about how to calculate how many local connections per endpoint your application needs based on expected traffic patterns, see [How to configure connections in Amazon Keyspaces](connections.md#connections.howtoconfigure).

1. **Retry policy** – Implement the Amazon Keyspaces retry policy `AmazonKeyspacesExponentialRetryPolicy` instead of the `DefaultRetryPolicy` that comes with the Cassandra driver. This allows you to configure the number of retry attempts for the `AmazonKeyspacesExponentialRetryPolicy` that meets your needs. By default, the number of retry attempts for the `AmazonKeyspacesExponentialRetryPolicy` is set to 3. For more information, see [How to configure the retry policy for connections in Amazon Keyspaces](connections.md#connections.retry-policies).

1. **Prepared statements** – Set `prepare-on-all-nodes` to false to optimize network usage.

```
datastax-java-driver {
    basic {
        contact-points = [ "cassandra.us-east-2.amazonaws.com:9142"]  
        request {
            timeout = 2 seconds
            consistency = LOCAL_QUORUM
            page-size = 1024
            default-idempotence = true
        }
        load-balancing-policy {
            local-datacenter = "us-east-2"
            class = DefaultLoadBalancingPolicy
            slow-replica-avoidance = false           
        }
    }
    advanced {
        auth-provider {
            class = software.aws.mcs.auth.SigV4AuthProvider
            aws-region = us-east-2
        }
        ssl-engine-factory {
            class = DefaultSslEngineFactory
            truststore-path = "./src/main/resources/cassandra_truststore.jks"
            truststore-password = "my_password"
            hostname-validation = false
        }
        connection {
	     connect-timeout = 5 seconds
	     max-requests-per-connection = 512
	     pool {
                local.size = 3
	     }
        }
       retry-policy {
           class =  com.aws.ssa.keyspaces.retry.AmazonKeyspacesExponentialRetryPolicy
	    max-attempts = 3
	    min-wait = 10 mills
	    max-wait = 100 mills
       }
       prepared-statements {
	    prepare-on-all-nodes = false
       }
    }
}
```

**Note**  
Instead of adding the path to the trustStore in the configuration file, you can also add the trustStore path directly in the application code or you can add the path to the trustStore to your JVM arguments.

### Step 3: Run the application
<a name="java_tutorial.SigV4.3"></a>

This code example shows a simple command line application that creates a connection pool to Amazon Keyspaces by using the configuration file we created earlier. It confirms that the connection is established by running a simple query.

```
package <your package>;
// add the following imports to your project
import com.datastax.oss.driver.api.core.CqlSession;
import com.datastax.oss.driver.api.core.config.DriverConfigLoader;
import com.datastax.oss.driver.api.core.cql.ResultSet;
import com.datastax.oss.driver.api.core.cql.Row;

public class App 
{
    
    public static void main( String[] args )
    {
        //Use DriverConfigLoader to load your configuration file
        DriverConfigLoader loader = DriverConfigLoader.fromClasspath("application.conf");
        try (CqlSession session = CqlSession.builder()
                .withConfigLoader(loader)
                .build()) {

            ResultSet rs = session.execute("select * from system_schema.keyspaces");
            Row row = rs.one();
            System.out.println(row.getString("keyspace_name"));
        }
    }
}
```

**Note**  
Use a `try` block to establish the connection to ensure that it's always closed. If you don't use a `try` block, remember to close your connection to avoid leaking resources.

## Connect to Amazon Keyspaces using the 3.x DataStax Java driver for Apache Cassandra and the SigV4 authentication plugin
<a name="java3x_tutorial.SigV4"></a>

The following section describes how to use the SigV4 authentication plugin for the 3.x open-source DataStax Java driver for Apache Cassandra to access Amazon Keyspaces. The plugin is available from the [GitHub repository](https://github.com/aws/aws-sigv4-auth-cassandra-java-driver-plugin/tree/3.x-Driver-Compatible).

The SigV4 authentication plugin allows you to use IAM credentials for users and roles when connecting to Amazon Keyspaces. Instead of requiring a user name and password, this plugin signs API requests using access keys. For more information, see [Create and configure AWS credentials for Amazon Keyspaces](access.credentials.md). 

### Step 1: Prerequisites
<a name="java3x_tutorial.SigV4.1"></a>

To run this code sample, you first need to complete the following tasks.
+ Create credentials for your IAM user or role following the steps at [Create and configure AWS credentials for Amazon Keyspaces](access.credentials.md). This tutorial assumes that the access keys are stored as environment variables. For more information, see [Store access keys for programmatic access](aws.credentials.manage.md).
+ Follow the steps at [Before you begin](#using_java_driver.BeforeYouBegin) to download the digital certificates, convert them to trustStore files, and attach the keystore in the JVM arguments to your application.
+ Add the DataStax Java driver for Apache Cassandra to your Java project. Ensure that you're using a version of the driver that supports Apache Cassandra 3.11.2. For more information, see the [DataStax Java Driver for Apache Cassandra documentation](https://github.com/datastax/java-driver).
+ Add the authentication plugin to your application. The authentication plugin supports version 3.x of the DataStax Java driver for Apache Cassandra. If you’re using Apache Maven, or a build system that can use Maven dependencies, add the following dependencies to your `pom.xml` file. Replace the version of the plugin with the latest version as shown at [GitHub repository](https://github.com/aws/aws-sigv4-auth-cassandra-java-driver-plugin/tree/3.x-Driver-Compatible).

  ```
  <dependency>
          <groupId>software.aws.mcs</groupId>
          <artifactId>aws-sigv4-auth-cassandra-java-driver-plugin_3</artifactId>
          <version>3.0.3</version>
  </dependency>
  ```

### Step 2: Run the application
<a name="java3x_tutorial.SigV4.3"></a>

This code example shows a simple command line application that creates a connection pool to Amazon Keyspaces. It confirms that the connection is established by running a simple query.

```
package <your package>;
// add the following imports to your project

import software.aws.mcs.auth.SigV4AuthProvider;  
import com.datastax.driver.core.Cluster;  
import com.datastax.driver.core.ResultSet;  
import com.datastax.driver.core.Row;  
import com.datastax.driver.core.Session;

public class App 
{
    
    public static void main( String[] args )
    {
        String endPoint = "cassandra.us-east-2.amazonaws.com";  
        int portNumber = 9142;
        Session session = Cluster.builder()  
	                                 .addContactPoint(endPoint)  
	                                 .withPort(portNumber)  
	                                 .withAuthProvider(new SigV4AuthProvider("us-east-2"))  
	                                 .withSSL()  
	                                 .build()  
	                                 .connect();

        ResultSet rs = session.execute("select * from system_schema.keyspaces");  
        Row row = rs.one();  
        System.out.println(row.getString("keyspace_name"));
    }
}
```

Usage notes:

For a list of available endpoints, see [Service endpoints for Amazon Keyspaces](programmatic.endpoints.md).

See the following repository for helpful Java driver policies, examples, and best practices when using the Java Driver with Amazon Keyspaces: [https://github.com/aws-samples/amazon-keyspaces-java-driver-helpers](https://github.com/aws-samples/amazon-keyspaces-java-driver-helpers). 

# Using a Cassandra Python client driver to access Amazon Keyspaces programmatically
<a name="using_python_driver"></a>

 In this section, we show you how to connect to Amazon Keyspaces using a Python client driver. To provide users and applications with credentials for programmatic access to Amazon Keyspaces resources, you can do either of the following:
+ Create service-specific credentials that are associated with a specific AWS Identity and Access Management (IAM) user.
+ For enhanced security, we recommend to create IAM access keys for IAM users or roles that are used across all AWS services. The Amazon Keyspaces SigV4 authentication plugin for Cassandra client drivers enables you to authenticate calls to Amazon Keyspaces using IAM access keys instead of user name and password. For more information, see [Create and configure AWS credentials for Amazon Keyspaces](access.credentials.md).

**Topics**
+ [Before you begin](#using_python_driver.BeforeYouBegin)
+ [Connect to Amazon Keyspaces using the Python driver for Apache Cassandra and service-specific credentials](#python_ssc)
+ [Connect to Amazon Keyspaces using the DataStax Python driver for Apache Cassandra and the SigV4 authentication plugin](#python_SigV4)

## Before you begin
<a name="using_python_driver.BeforeYouBegin"></a>

You need to complete the following task before you can start.

Amazon Keyspaces requires the use of Transport Layer Security (TLS) to help secure connections with clients. To connect to Amazon Keyspaces using TLS, you need to download Amazon digital certificates and configure the Python driver to use TLS. 

 Download the following digital certificates and save the files locally or in your home directory.

1. AmazonRootCA1

1. AmazonRootCA2

1. AmazonRootCA3

1. AmazonRootCA4

1. Starfield Class 2 Root (optional – for backward compatibility)

To download the certificates, you can use the following commands.

```
curl -O https://www.amazontrust.com/repository/AmazonRootCA1.pem
curl -O https://www.amazontrust.com/repository/AmazonRootCA2.pem
curl -O https://www.amazontrust.com/repository/AmazonRootCA3.pem
curl -O https://www.amazontrust.com/repository/AmazonRootCA4.pem
curl -O https://certs.secureserver.net/repository/sf-class2-root.crt
```

**Note**  
Amazon Keyspaces previously used TLS certificates anchored to the Starfield Class 2 CA. AWS is migrating all AWS Regions to certificates issued under Amazon Trust Services (Amazon Root CAs 1–4). During this transition, configure clients to trust both Amazon Root CAs 1–4 and the Starfield root to ensure compatibility across all Regions.

Combine all downloaded certificates into a single `pem` file with the name *keyspaces-bundle.pem* in our examples. You can do this by running the following command. Take note of the path to the file, you need this later.

```
cat AmazonRootCA1.pem \
 AmazonRootCA2.pem \
 AmazonRootCA3.pem \
 AmazonRootCA4.pem \
 sf-class2-root.crt \
 > keyspaces-bundle.pem
```

## Connect to Amazon Keyspaces using the Python driver for Apache Cassandra and service-specific credentials
<a name="python_ssc"></a>

The following code example shows you how to connect to Amazon Keyspaces with a Python client driver and service-specific credentials.

```
from cassandra.cluster import Cluster
from ssl import SSLContext, PROTOCOL_TLSv1_2 , CERT_REQUIRED
from cassandra.auth import PlainTextAuthProvider

ssl_context = SSLContext(PROTOCOL_TLSv1_2 )

ssl_context.load_verify_locations('path_to_file/keyspaces-bundle.pem')

ssl_context.verify_mode = CERT_REQUIRED
auth_provider = PlainTextAuthProvider(username='ServiceUserName', password='ServicePassword')
cluster = Cluster(['cassandra.us-east-2.amazonaws.com'], ssl_context=ssl_context, auth_provider=auth_provider, port=9142)
session = cluster.connect()
r = session.execute('select * from system_schema.keyspaces')
print(r.current_rows)
```

Usage notes:

1. Replace `"path_to_file/keyspaces-bundle.pem"` with the path to the combined certificate file saved in the first step.

1. Ensure that the *ServiceUserName* and *ServicePassword* match the user name and password you obtained when you generated the service-specific credentials by following the steps to [Create service-specific credentials for programmatic access to Amazon Keyspaces](programmatic.credentials.ssc.md). 

1. For a list of available endpoints, see [Service endpoints for Amazon Keyspaces](programmatic.endpoints.md).

## Connect to Amazon Keyspaces using the DataStax Python driver for Apache Cassandra and the SigV4 authentication plugin
<a name="python_SigV4"></a>

The following section shows how to use the SigV4 authentication plugin for the open-source DataStax Python driver for Apache Cassandra to access Amazon Keyspaces (for Apache Cassandra). 

If you haven't already done so, begin with creating credentials for your IAM role following the steps at [Create and configure AWS credentials for Amazon Keyspaces](access.credentials.md). This tutorial uses temporary credentials, which requires an IAM role. For more information about temporary credentials, see [Create temporary credentials to connect to Amazon Keyspaces using an IAM role and the SigV4 plugin](temporary.credentials.IAM.md).

Then, add the Python SigV4 authentication plugin to your environment from the [GitHub repository](https://github.com/aws/aws-sigv4-auth-cassandra-python-driver-plugin).

```
pip install cassandra-sigv4
```

The following code example shows how to connect to Amazon Keyspaces by using the open-source DataStax Python driver for Cassandra and the SigV4 authentication plugin. The plugin depends on the AWS SDK for Python (Boto3). It uses `boto3.session` to obtain temporary credentials. 

```
from cassandra.cluster import Cluster
from ssl import SSLContext, PROTOCOL_TLSv1_2 , CERT_REQUIRED
from cassandra.auth import PlainTextAuthProvider
import boto3
from cassandra_sigv4.auth import SigV4AuthProvider

ssl_context = SSLContext(PROTOCOL_TLSv1_2)
ssl_context.load_verify_locations('path_to_file/keyspaces-bundle.pem')
ssl_context.verify_mode = CERT_REQUIRED

# use this if you want to use Boto to set the session parameters.
boto_session = boto3.Session(aws_access_key_id="AKIAIOSFODNN7EXAMPLE",
                             aws_secret_access_key="wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
                             aws_session_token="AQoDYXdzEJr...<remainder of token>",
                             region_name="us-east-2")
auth_provider = SigV4AuthProvider(boto_session)

# Use this instead of the above line if you want to use the Default Credentials and not bother with a session.
# auth_provider = SigV4AuthProvider()

cluster = Cluster(['cassandra.us-east-2.amazonaws.com'], ssl_context=ssl_context, auth_provider=auth_provider,
                  port=9142)
session = cluster.connect()
r = session.execute('select * from system_schema.keyspaces')
print(r.current_rows)
```

Usage notes:

1. Replace `"path_to_file/keyspaces-bundle.pem"` with the path to the certificate saved in the first step.

1. Ensure that the *aws\$1access\$1key\$1id*, *aws\$1secret\$1access\$1key*, and the *aws\$1session\$1token* match the `Access Key`, `Secret Access Key`, and `Session Token` you obtained using `boto3.session`. For more information, see [Credentials](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html) in the *AWS SDK for Python (Boto3)*. 

1. For a list of available endpoints, see [Service endpoints for Amazon Keyspaces](programmatic.endpoints.md).

# Using a Cassandra Node.js client driver to access Amazon Keyspaces programmatically
<a name="using_nodejs_driver"></a>

 This section shows you how to connect to Amazon Keyspaces by using a Node.js client driver. To provide users and applications with credentials for programmatic access to Amazon Keyspaces resources, you can do either of the following:
+ Create service-specific credentials that are associated with a specific AWS Identity and Access Management (IAM) user.
+ For enhanced security, we recommend to create IAM access keys for IAM users or roles that are used across all AWS services. The Amazon Keyspaces SigV4 authentication plugin for Cassandra client drivers enables you to authenticate calls to Amazon Keyspaces using IAM access keys instead of user name and password. For more information, see [Create and configure AWS credentials for Amazon Keyspaces](access.credentials.md).

**Topics**
+ [Before you begin](#using_nodejs_driver.BeforeYouBegin)
+ [Connect to Amazon Keyspaces using the Node.js DataStax driver for Apache Cassandra and service-specific credentials](#nodejs_ssc)
+ [Connect to Amazon Keyspaces using the DataStax Node.js driver for Apache Cassandra and the SigV4 authentication plugin](#nodejs_SigV4)

## Before you begin
<a name="using_nodejs_driver.BeforeYouBegin"></a>

You need to complete the following task before you can start.

Amazon Keyspaces requires the use of Transport Layer Security (TLS) to help secure connections with clients. To connect to Amazon Keyspaces using TLS, you need to download an Amazon digital certificate and configure the Python driver to use TLS. 

 Download the following digital certificates and save the files locally or in your home directory.

1. AmazonRootCA1

1. AmazonRootCA2

1. AmazonRootCA3

1. AmazonRootCA4

1. Starfield Class 2 Root (optional – for backward compatibility)

To download the certificates, you can use the following commands.

```
curl -O https://www.amazontrust.com/repository/AmazonRootCA1.pem
curl -O https://www.amazontrust.com/repository/AmazonRootCA2.pem
curl -O https://www.amazontrust.com/repository/AmazonRootCA3.pem
curl -O https://www.amazontrust.com/repository/AmazonRootCA4.pem
curl -O https://certs.secureserver.net/repository/sf-class2-root.crt
```

**Note**  
Amazon Keyspaces previously used TLS certificates anchored to the Starfield Class 2 CA. AWS is migrating all AWS Regions to certificates issued under Amazon Trust Services (Amazon Root CAs 1–4). During this transition, configure clients to trust both Amazon Root CAs 1–4 and the Starfield root to ensure compatibility across all Regions.

Combine all downloaded certificates into a single `pem` file with the name *keyspaces-bundle.pem* in our examples. You can do this by running the following command. Take note of the path to the file, you need this later.

```
cat AmazonRootCA1.pem \
 AmazonRootCA2.pem \
 AmazonRootCA3.pem \
 AmazonRootCA4.pem \
 sf-class2-root.crt \
 > keyspaces-bundle.pem
```

## Connect to Amazon Keyspaces using the Node.js DataStax driver for Apache Cassandra and service-specific credentials
<a name="nodejs_ssc"></a>

 Configure your driver to use the combined certificate file `keyspaces-bundle.pem` for TLS and authenticate using service-specific credentials. For example: 

```
const cassandra = require('cassandra-driver');
const fs = require('fs');
const auth = new cassandra.auth.PlainTextAuthProvider('ServiceUserName', 'ServicePassword');
const sslOptions1 = {
         ca: [
                    fs.readFileSync('path_to_file/keyspaces-bundle.pem', 'utf-8')],      
                    host: 'cassandra.us-west-2.amazonaws.com',
                    rejectUnauthorized: true
        };
const client = new cassandra.Client({
                   contactPoints: ['cassandra.us-west-2.amazonaws.com'],
                   localDataCenter: 'us-west-2',
                   authProvider: auth,
                   sslOptions: sslOptions1,
                   protocolOptions: { port: 9142 }
        });
const query = 'SELECT * FROM system_schema.keyspaces';
 
client.execute(query)
                    .then( result => console.log('Row from Keyspaces %s', result.rows[0]))
                    .catch( e=> console.log(`${e}`));
```

Usage notes:

1. Replace `"path_to_file/keyspaces-bundle.pem"` with the path to the combined certificate file saved in the first step.

1. Ensure that the *ServiceUserName* and *ServicePassword* match the user name and password you obtained when you generated the service-specific credentials by following the steps to [Create service-specific credentials for programmatic access to Amazon Keyspaces](programmatic.credentials.ssc.md). 

1. For a list of available endpoints, see [Service endpoints for Amazon Keyspaces](programmatic.endpoints.md).

## Connect to Amazon Keyspaces using the DataStax Node.js driver for Apache Cassandra and the SigV4 authentication plugin
<a name="nodejs_SigV4"></a>

The following section shows how to use the SigV4 authentication plugin for the open-source DataStax Node.js driver for Apache Cassandra to access Amazon Keyspaces (for Apache Cassandra). 

If you haven't already done so, create credentials for your IAM user or role following the steps at [Create and configure AWS credentials for Amazon Keyspaces](access.credentials.md).

Add the Node.js SigV4 authentication plugin to your application from the [GitHub repository](https://github.com/aws/aws-sigv4-auth-cassandra-nodejs-driver-plugin). The plugin supports version 4.x of the DataStax Node.js driver for Cassandra and depends on the AWS SDK for Node.js. It uses `AWSCredentialsProvider` to obtain credentials.

```
$ npm install aws-sigv4-auth-cassandra-plugin --save
```

This code example shows how to set a Region-specific instance of `SigV4AuthProvider` as the authentication provider.

```
const cassandra = require('cassandra-driver');
const fs = require('fs');
const sigV4 = require('aws-sigv4-auth-cassandra-plugin');

const auth = new sigV4.SigV4AuthProvider({
    region: 'us-west-2', 
    accessKeyId:'AKIAIOSFODNN7EXAMPLE',
    secretAccessKey: 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY'});

const sslOptions1 = {
  ca: [
      fs.readFileSync('path_to_file/keyspaces-bundle.pem', 'utf-8')],
  host: 'cassandra.us-west-2.amazonaws.com',
  rejectUnauthorized: true
};


const client = new cassandra.Client({
  contactPoints: ['cassandra.us-west-2.amazonaws.com'],
  localDataCenter: 'us-west-2',
  authProvider: auth,
  sslOptions: sslOptions1,
  protocolOptions: { port: 9142 }
});


const query = 'SELECT * FROM system_schema.keyspaces';

client.execute(query).then(
    result => console.log('Row from Keyspaces %s', result.rows[0]))
    .catch( e=> console.log(`${e}`));
```

Usage notes:

1. Replace `"path_to_file/keyspaces-bundle.pem"` with the path to the certificate saved in the first step.

1. Ensure that the *accessKeyId* and *secretAccessKey* match the Access Key and Secret Access Key you obtained using `AWSCredentialsProvider`. For more information, see [Setting Credentials in Node.js](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-credentials-node.html) in the *AWS SDK for JavaScript in Node.js*. 

1. To store access keys outside of code, see best practices at [Store access keys for programmatic access](aws.credentials.manage.md).

1. For a list of available endpoints, see [Service endpoints for Amazon Keyspaces](programmatic.endpoints.md).

# Using a Cassandra .NET Core client driver to access Amazon Keyspaces programmatically
<a name="using_dotnetcore_driver"></a>

This section shows you how to connect to Amazon Keyspaces by using a .NET Core client driver. The setup steps will vary depending on your environment and operating system, you might have to modify them accordingly. Amazon Keyspaces requires the use of Transport Layer Security (TLS) to help secure connections with clients. To connect to Amazon Keyspaces using TLS, configure your driver to use the system trust store, which includes the Amazon Root CAs 1-4.

1.  Install the CassandraCSharpDriver through nuget, using the nuget console. 

   ```
   PM> Install-Package CassandraCSharpDriver
   ```

1. The following example uses a .NET Core C\$1 console project to connect to Amazon Keyspaces and run a query.

   ```
   using Cassandra;
   using System;
   using System.Collections.Generic;
   using System.Linq;
   using System.Net.Security;
   using System.Runtime.ConstrainedExecution;
   using System.Security.Cryptography.X509Certificates;
   using System.Text;
   using System.Threading.Tasks;
   
   namespace CSharpKeyspacesExample
   {
       class Program
       {
           public Program(){}
   
           static void Main(string[] args)
           {
               var userName = "ServiceUserName";
               var pwd = "ServicePassword";
               certCollection.Add(amazoncert);
    
               var awsEndpoint =  "cassandra.us-east-2.amazonaws.com" ;  
   
               var cluster = Cluster.Builder()
                        .AddContactPoints(awsEndpoint)
                        .WithPort(9142)
                        .WithAuthProvider(new PlainTextAuthProvider(userName, pwd))
                        .WithSSL(new SSLOptions().SetCertificateCollection(certCollection))
                        .Build();
   
               var session = cluster.Connect();
               var rs = session.Execute("SELECT * FROM system_schema.tables;");
               foreach (var row in rs)
               {
                   var name = row.GetValue<String>("keyspace_name");
                   Console.WriteLine(name);
               }
           }
       }
   }
   ```

Usage notes:

1. Ensure that you use the default system trust store, which includes the Amazon Root CAs 1-4.

1. Ensure that the *ServiceUserName* and *ServicePassword* match the user name and password you obtained when you generated the service-specific credentials by following the steps to [Create service-specific credentials for programmatic access to Amazon Keyspaces](programmatic.credentials.ssc.md). 

1. For a list of available endpoints, see [Service endpoints for Amazon Keyspaces](programmatic.endpoints.md).

# Using a Cassandra Go client driver to access Amazon Keyspaces programmatically
<a name="using_go_driver"></a>

This section shows you how to connect to Amazon Keyspaces by using a Go Cassandra client driver. To provide users and applications with credentials for programmatic access to Amazon Keyspaces resources, you can do either of the following:
+ Create service-specific credentials that are associated with a specific AWS Identity and Access Management (IAM) user.
+ For enhanced security, we recommend to create IAM access keys for IAM principals that are used across all AWS services. The Amazon Keyspaces SigV4 authentication plugin for Cassandra client drivers enables you to authenticate calls to Amazon Keyspaces using IAM access keys instead of user name and password. For more information, see [Create and configure AWS credentials for Amazon Keyspaces](access.credentials.md).

**Topics**
+ [Before you begin](#using_go_driver.BeforeYouBegin)
+ [Connect to Amazon Keyspaces using the Gocql driver for Apache Cassandra and service-specific credentials](#go_ssc)
+ [Connect to Amazon Keyspaces using the Go driver for Apache Cassandra and the SigV4 authentication plugin](#go_SigV4)

## Before you begin
<a name="using_go_driver.BeforeYouBegin"></a>

You need to complete the following task before you can start.

Amazon Keyspaces requires the use of Transport Layer Security (TLS) to help secure connections with clients. To connect to Amazon Keyspaces using TLS, you need to download an Amazon digital certificate and configure the Go driver to use TLS. 

 Download the following digital certificates and save the files locally or in your home directory.

1. AmazonRootCA1

1. AmazonRootCA2

1. AmazonRootCA3

1. AmazonRootCA4

1. Starfield Class 2 Root (optional – for backward compatibility)

To download the certificates, you can use the following commands.

```
curl -O https://www.amazontrust.com/repository/AmazonRootCA1.pem
curl -O https://www.amazontrust.com/repository/AmazonRootCA2.pem
curl -O https://www.amazontrust.com/repository/AmazonRootCA3.pem
curl -O https://www.amazontrust.com/repository/AmazonRootCA4.pem
curl -O https://certs.secureserver.net/repository/sf-class2-root.crt
```

**Note**  
Amazon Keyspaces previously used TLS certificates anchored to the Starfield Class 2 CA. AWS is migrating all AWS Regions to certificates issued under Amazon Trust Services (Amazon Root CAs 1–4). During this transition, configure clients to trust both Amazon Root CAs 1–4 and the Starfield root to ensure compatibility across all Regions.

Combine all downloaded certificates into a single `pem` file with the name *keyspaces-bundle.pem* in our examples. You can do this by running the following command. Take note of the path to the file, you need this later.

```
cat AmazonRootCA1.pem \
 AmazonRootCA2.pem \
 AmazonRootCA3.pem \
 AmazonRootCA4.pem \
 sf-class2-root.crt \
 > keyspaces-bundle.pem
```

## Connect to Amazon Keyspaces using the Gocql driver for Apache Cassandra and service-specific credentials
<a name="go_ssc"></a>

1. Create a directory for your application.

   ```
   mkdir ./gocqlexample
   ```

1. Navigate to the new directory.

   ```
   cd gocqlexample
   ```

1. Create a file for your application.

   ```
   touch cqlapp.go
   ```

1. Download the Go driver. 

   ```
   go get github.com/gocql/gocql
   ```

1. Add the following sample code to the cqlapp.go file.

   ```
   package main
   
   import (
   	    "fmt"
   	    "github.com/gocql/gocql"
   	    "log"
   )
   
   func main() {
   
       // add the Amazon Keyspaces service endpoint 
       cluster := gocql.NewCluster("cassandra.us-east-2.amazonaws.com")
       cluster.Port=9142
       // add your service specific credentials
       cluster.Authenticator = gocql.PasswordAuthenticator{
               Username: "ServiceUserName",
               Password: "ServicePassword"}
   
       // provide the path to the keyspaces-bundle.pem
       cluster.SslOpts = &gocql.SslOptions{
               CaPath: "path_to_file/keyspaces-bundle.pem",
               EnableHostVerification: false,            
        }
   
        // Override default Consistency to LocalQuorum
        cluster.Consistency = gocql.LocalQuorum
        cluster.DisableInitialHostLookup = false
   
        session, err := cluster.CreateSession()
        if err != nil {
               fmt.Println("err>", err)
        }
        defer session.Close()
   
        // run a sample query from the system keyspace
        var text string
        iter := session.Query("SELECT keyspace_name FROM system_schema.tables;").Iter()
        for iter.Scan(&text) {
               fmt.Println("keyspace_name:", text)
        }
        if err := iter.Close(); err != nil {
               log.Fatal(err)
        }
        session.Close()
   }
   ```

   Usage notes:

   1. Replace `"path_to_file/keyspaces-bundle.pem"` with the path to the combined certificate file saved in the first step.

   1. Ensure that the *ServiceUserName* and *ServicePassword* match the user name and password you obtained when you generated the service-specific credentials by following the steps to [Create service-specific credentials for programmatic access to Amazon Keyspaces](programmatic.credentials.ssc.md). 

   1. For a list of available endpoints, see [Service endpoints for Amazon Keyspaces](programmatic.endpoints.md).

1. Build the program.

   ```
   go build cqlapp.go
   ```

1. Run the program.

   ```
   ./cqlapp
   ```

## Connect to Amazon Keyspaces using the Go driver for Apache Cassandra and the SigV4 authentication plugin
<a name="go_SigV4"></a>

The following code sample shows how to use the SigV4 authentication plugin for the open-source Go driver to access Amazon Keyspaces (for Apache Cassandra). 

If you haven't already done so, create credentials for your IAM principal following the steps at [Create and configure AWS credentials for Amazon Keyspaces](access.credentials.md). If an application is running on Lambda or an Amazon EC2 instance, your application is automatically using the credentials of the instance. To run this tutorial locally, you can store the credentials as local environment variables.

Add the Go SigV4 authentication plugin to your application from the [GitHub repository](https://github.com/aws/aws-sigv4-auth-cassandra-gocql-driver-plugin). The plugin supports version 1.2.x of the open-source Go driver for Cassandra and depends on the AWS SDK for Go.

```
$ go mod init
$ go get github.com/aws/aws-sigv4-auth-cassandra-gocql-driver-plugin
```

In this code example, the Amazon Keyspaces endpoint is represented by the `Cluster` class. It uses the `AwsAuthenticator` for the authenticator property of the cluster to obtain credentials.

```
package main

import (
        "fmt"
        "github.com/aws/aws-sigv4-auth-cassandra-gocql-driver-plugin/sigv4"
        "github.com/gocql/gocql"
        "log"
)

func main() {
    // configuring the cluster options
    cluster := gocql.NewCluster("cassandra.us-west-2.amazonaws.com")
    cluster.Port=9142
    
    // the authenticator uses the default credential chain to find AWS credentials
    cluster.Authenticator = sigv4.NewAwsAuthenticator()

    cluster.SslOpts = &gocql.SslOptions{

            CaPath: "path_to_file/keyspaces-bundle.pem",
            EnableHostVerification: false,
    }
    cluster.Consistency = gocql.LocalQuorum
    cluster.DisableInitialHostLookup = false
   
    session, err := cluster.CreateSession()
    if err != nil {
	    fmt.Println("err>", err)
	    return
    }
    defer session.Close()

    // doing the query
    var text string
    iter := session.Query("SELECT keyspace_name FROM system_schema.tables;").Iter()
    for iter.Scan(&text) {
	    fmt.Println("keyspace_name:", text)
    }
    if err := iter.Close(); err != nil {
	    log.Fatal(err)
    }
}
```

Usage notes:

1. Replace `"path_to_file/keyspaces-bundle.pem"` with the path to the certificate file saved in the first step.

1. For this example to run locally, you need to define the following variables as environment variables:
   + `AWS_ACCESS_KEY_ID`
   + `AWS_SECRET_ACCESS_KEY`
   + `AWS_DEFAULT_REGION`

1. To store access keys outside of code, see best practices at [Store access keys for programmatic access](aws.credentials.manage.md).

1. For a list of available endpoints, see [Service endpoints for Amazon Keyspaces](programmatic.endpoints.md).

# Using a Cassandra Perl client driver to access Amazon Keyspaces programmatically
<a name="using_perl_driver"></a>

This section shows you how to connect to Amazon Keyspaces by using a Perl client driver. For this code sample, we used Perl 5. Amazon Keyspaces requires the use of Transport Layer Security (TLS) to help secure connections with clients. 

**Important**  
Amazon Keyspacescertificates are transitioning to the Amazon Trust Services (ATS) hierarchy. Ensure your environment trusts the Amazon Root CAs 1–4 to avoid connection errors during this rotation. The Perl driver doesn't validate the server's Amazon SSL certificate, which means that you can't confirm that you are connecting to Amazon Keyspaces. The second step, to configure the driver to use TLS when connecting to Amazon Keyspaces is still required, and ensures that data transferred between the client and server is encrypted. 

1. Download the Cassandra DBI driver from [https://metacpan.org/pod/DBD::Cassandra](https://metacpan.org/pod/DBD::Cassandra) and install the driver to your Perl environment. The exact steps depend on the environment. The following is a common example.

   ```
   cpanm DBD::Cassandra
   ```

1. Create a file for your application.

   ```
   touch cqlapp.pl
   ```

1. Add the following sample code to the cqlapp.pl file.

   ```
   use DBI;
   my $user = "ServiceUserName";
   my $password = "ServicePassword";
   my $db = DBI->connect("dbi:Cassandra:host=cassandra.us-east-2.amazonaws.com;port=9142;tls=1;", 
   $user, $password);
   
   my $rows = $db->selectall_arrayref("select * from system_schema.keyspaces"); 
   print "Found the following Keyspaces...\n"; 
   for my $row (@$rows) { 
         print join(" ",@$row['keyspace_name']),"\n"; 
   } 
   
   $db->disconnect;
   ```
**Important**  
 Ensure that the *ServiceUserName* and *ServicePassword* match the user name and password you obtained when you generated the service-specific credentials by following the steps to [Create service-specific credentials for programmatic access to Amazon Keyspaces](programmatic.credentials.ssc.md). 
**Note**  
For a list of available endpoints, see [Service endpoints for Amazon Keyspaces](programmatic.endpoints.md).

1. Run the application.

   ```
   perl cqlapp.pl
   ```

# Configure cross-account access to Amazon Keyspaces with VPC endpoints
<a name="access.cross-account"></a>

You can create and use separate AWS accounts to isolate resources and for use in different environments, for example development and production. This topic walks you through cross-account access for Amazon Keyspaces using interface VPC endpoints in an Amazon Virtual Private Cloud. For more information about IAM cross-account access configuration, see [Example scenario using separate development and production accounts](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_common-scenarios_aws-accounts.html#id_roles_common-scenarios_aws-accounts-example) in the IAM User Guide. 

For more information about Amazon Keyspaces and private VPC endpoints, see [Using Amazon Keyspaces with interface VPC endpoints](vpc-endpoints.md).

**Topics**
+ [Configure cross-account access in a shared VPC](access.cross-account.sharedVPC.md)
+ [Configure cross-account access without a shared VPC](access.cross-account.noVPC.setup.md)

# Configure cross-account access to Amazon Keyspaces using VPC endpoints in a shared VPC
<a name="access.cross-account.sharedVPC"></a>

You can create different AWS accounts to separate resources from applications. For example, you can create one account for your Amazon Keyspaces tables, a different account for applications in a development environment, and another account for applications in a production environment. This topic walks you through the configuration steps required to set up cross-account access for Amazon Keyspaces using interface VPC endpoints in a shared VPC. 

For detailed steps how to configure a VPC endpoint for Amazon Keyspaces, see [Step 3: Create a VPC endpoint for Amazon Keyspaces](vpc-endpoints-tutorial.create-endpoint.md).

In this example we use the following three accounts in a shared VPC:
+ `Account A:111111111111` – This account contains infrastructure, including the VPC endpoints, the VPC subnets, and Amazon Keyspaces tables. 
+ `Account B:222222222222` – This account contains an application in a development environment that needs to connect to the Amazon Keyspaces table in `Account A:111111111111`. 
+ `Account C:333333333333` – This account contains an application in a production environment that needs to connect to the Amazon Keyspaces table in `Account A:111111111111`.

![\[Diagram showing three different accounts in owned by the same organization in the same AWS Region that use a shared VPC.\]](http://docs.aws.amazon.com/keyspaces/latest/devguide/images/keyspaces_cross-account_sharedVPC.png)


`Account A:111111111111` is the account that contains the resources (an Amazon Keyspaces table) that `Account B:222222222222` and `Account C:333333333333` need to access, so `Account A:111111111111` is the *trusting* account. `Account B:222222222222` and `Account C:333333333333` are the accounts with the principals that need access to the resources (an Amazon Keyspaces table) in `Account A:111111111111`, so `Account B:222222222222` and `Account C:333333333333` are the *trusted* accounts. The trusting account grants the permissions to the trusted accounts by sharing an IAM role. The following procedure outlines the configuration steps required in `Account A:111111111111`.

**Configuration for `Account A:111111111111`**

1. Use AWS Resource Access Manager to create a resource share for the subnet and share the private subnet with `Account B:222222222222` and `Account C:333333333333`.

   `Account B:222222222222` and `Account C:333333333333` can now see and create resources in the subnet that has been shared with them. 

1. Create an Amazon Keyspaces private VPC endpoint powered by AWS PrivateLink. This creates multiple endpoints across shared subnets and DNS entries for the Amazon Keyspaces service endpoint.

1. Create an Amazon Keyspaces keyspace and table.

1. Create an IAM role in `Account A:111111111111` that has full access to the Amazon Keyspaces table, read access to the Amazon Keyspaces system tables, and is able to describe the Amazon EC2 VPC resources as shown in the following policy example.

   ```
   {
       "Version": "2012-10-17",		 	 	 
       "Statement": [
           {
               "Sid": "CrossAccountAccess",
               "Effect": "Allow",
               "Action": [
                   "ec2:DescribeNetworkInterfaces",
                   "ec2:DescribeVpcEndpoints",
                   "cassandra:*"
               ],
               "Resource": "*"
           }
       ]
   }
   ```

1. Configure a trust policy for the IAM role in `Account A:111111111111` so that `Account B:222222222222` and `Account C:333333333333` can assume the role as trusted accounts. This is shown in the following example. 

   ```
   {
     "Version": "2012-10-17",		 	 	 
     "Statement": [
       {
         "Effect": "Allow",
         "Principal": {
           "AWS": [
             "arn:aws:iam::222222222222:role/Cross-Account-Role-B",
             "arn:aws:iam::333333333333:role/Cross-Account-Role-C"
           ]
         },
         "Action": "sts:AssumeRole",
         "Condition": {}
       }
     ]
   }
   ```

   For more information about cross-account IAM policies, see [Cross-account policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic-cross-account.html) in the IAM User Guide.

**Configuration in `Account B:222222222222` and `Account C:333333333333`**

1. In `Account B:222222222222` and `Account C:333333333333`, create new roles and attach the following policy that allows the principal to assume the shared role created in `Account A:111111111111`.

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

   Allowing the principal to assume the shared role is implemented using the `AssumeRole` API of the AWS Security Token Service (AWS STS). For more information, see [ Providing access to an IAM user in another AWS account that you own](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_common-scenarios_aws-accounts.html) in the IAM User Guide. 

1. In `Account B:222222222222` and `Account C:333333333333`, you can create applications that utilize the SIGV4 authentication plugin, which allows an application to assume the shared role to connect to the Amazon Keyspaces table located in `Account A:111111111111` through the VPC endpoint in the shared VPC. For more information about the SIGV4 authentication plugin, see [Create credentials for programmatic access to Amazon Keyspaces](programmatic.credentials.md). For more information on how to configure an application to assume a role in another AWS account, see [Authentication and access](https://docs.aws.amazon.com/sdkref/latest/guide/access.html) in the *AWS SDKs and Tools Reference Guide*.

# Configuring cross-account access to Amazon Keyspaces without a shared VPC
<a name="access.cross-account.noVPC.setup"></a>

If the Amazon Keyspaces table and private VPC endpoint are owned by different accounts but are not sharing a VPC, applications can still connect cross-account using VPC endpoints. Because the accounts are not sharing the VPC endpoints, `Account A:111111111111`, `Account B:222222222222`, and `Account C:333333333333` require their own VPC endpoints. To the Cassandra client driver, Amazon Keyspaces appears like a single node instead of a multi-node cluster. Upon connection, the client driver reaches the DNS server which returns one of the available endpoints in the account’s VPC. 

You can also access Amazon Keyspaces tables across different accounts without a shared VPC endpoint by using the public endpoints or deploying a private VPC endpoint in each account. When not using a shared VPC, each account requires its own VPC endpoint. In this example `Account A:111111111111`, `Account B:222222222222`, and `Account C:333333333333` require their own VPC endpoints to access the table in `Account A:111111111111`. When using VPC endpoints in this configuration, Amazon Keyspaces appears as a single node cluster to the Cassandra client driver instead of a multi-node cluster. Upon connection, the client driver reaches the DNS server which returns one of the available endpoints in the account’s VPC. But the client driver is not able to access the `system.peers` table to discover additional endpoints. Because there are less hosts available, the driver makes less connections. To adjust this, increase the connection pool setting of the driver by a factor of three. 

![\[Diagram showing three different accounts in owned by the same organization in the same AWS Region without a shared VPC.\]](http://docs.aws.amazon.com/keyspaces/latest/devguide/images/keyspaces_cross-account_noVPC.png)


`Account A:111111111111` is the account that contains the resources (an Amazon Keyspaces table) that `Account B:222222222222` and `Account C:333333333333` need to access, so `Account A:111111111111` is the *trusting* account. `Account B:222222222222` and `Account C:333333333333` are the accounts with the principals that need access to the resources (an Amazon Keyspaces table) in `Account A:111111111111`, so `Account B:222222222222` and `Account C:333333333333` are the *trusted* accounts. The trusting account grants the permissions to the trusted accounts by sharing an IAM role. The following procedure outlines the configuration steps required in `Account A:111111111111`.

**Configuration for `Account A:111111111111`**

1. Create an Amazon Keyspaces keyspace and table in `Account A:111111111111`.

1. Create an IAM role in `Account A:111111111111` that has full access to the Amazon Keyspaces table and read access to the Amazon Keyspaces system tables.

   ```
   {
      "Version":"2012-10-17",		 	 	 
      "Statement":[
         {
            "Effect":"Allow",
            "Action":[
               "cassandra:Select",
               "cassandra:Modify"
            ],
            "Resource":[
               "arn:aws:cassandra:us-east-1:111111111111:/keyspace/mykeyspace/table/mytable",
               "arn:aws:cassandra:us-east-1:111111111111:/keyspace/system*"
            ]
         }
      ]
   }
   ```

1. Configure a trust policy for the IAM role in `Account A:111111111111` so that principals in `Account B:222222222222` and `Account C:333333333333` can assume the role as trusted accounts. This is shown in the following example. 

   ```
   {
     "Version": "2012-10-17",		 	 	 
     "Statement": [
       {
         "Effect": "Allow",
         "Principal": {
           "AWS": [
             "arn:aws:iam::222222222222:role/Cross-Account-Role-B",
             "arn:aws:iam::333333333333:role/Cross-Account-Role-C"
           ]
         },
         "Action": "sts:AssumeRole",
         "Condition": {}
       }
     ]
   }
   ```

   For more information about cross-account IAM policies, see [Cross-account policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic-cross-account.html) in the IAM User Guide.

1. Configure the VPC endpoint in `Account A:111111111111` and attach permissions to the endpoint that allow the roles from `Account B:222222222222` and `Account C:333333333333` to assume the role in `Account A` using the VPC endpoint. These permissions are valid for the VPC endpoint that they are attached to. For more information about VPC endpoint policies, see [Controlling access to interface VPC endpoints for Amazon Keyspaces](vpc-endpoints.md#interface-vpc-endpoints-policies).

   ```
   {{
     "Version": "2012-10-17",		 	 	 
     "Statement": [
       {
         "Sid": "AllowAccessfromSpecificIAMroles",
         "Effect": "Allow",
         "Action": "cassandra:*",
         "Resource": "*",
         "Principal": "*",
         "Condition": {
           "ArnEquals": {
             "aws:PrincipalArn": [
               "arn:aws:iam::222222222222:role/Cross-Account-Role-B",
               "arn:aws:iam::333333333333:role/Cross-Account-Role-C"
             ]
           }
         }
       }
     ]
   }
   ```

**Configuration in `Account B:222222222222` and `Account C:333333333333`**

1. In `Account B:222222222222` and `Account C:333333333333`, create new roles and attach the following policy that allows the principal to assume the shared role created in `Account A:111111111111`.

   ```
   {
       "Version": "2012-10-17",		 	 	 
       "Statement": {
               "Effect": "Allow",
               "Action": "sts:AssumeRole",
               "Resource": "arn:aws:iam::111111111111:role/keyspaces_access"
           }
   }
   ```

   Allowing the principal to assume the shared role is implemented using the `AssumeRole` API of the AWS Security Token Service (AWS STS). For more information, see [ Providing access to an IAM user in another AWS account that you own](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_common-scenarios_aws-accounts.html) in the IAM User Guide. 

1. In `Account B:222222222222` and `Account C:333333333333`, you can create applications that utilize the SIGV4 authentication plugin, which allows an application to assume the shared role to connect to the Amazon Keyspaces table located in `Account A:111111111111`. For more information about the SIGV4 authentication plugin, see [Create credentials for programmatic access to Amazon Keyspaces](programmatic.credentials.md). For more information on how to configure an application to assume a role in another AWS account, see [Authentication and access](https://docs.aws.amazon.com/sdkref/latest/guide/access.html) in the *AWS SDKs and Tools Reference Guide*.