Connect with legacy drivers

If the driver you are using doesn’t support the DataStax Astra DB secure connect bundle and you are unable to upgrade, you can still connect to Astra DB with additional steps. To connect, collect connection information from the secure connect bundle and set up the required SSL context for your driver to speak with Astra DB.

Prerequisites

Working with secure connect bundle

Downloading secure connect bundle

To connect to your Astra DB database using the drivers, download the secure database bundle from the DataStax Astra DB console that contains the connection credentials.

  1. Open a browser, navigate to Astra DB, and log in.

  1. From your Dashboard page, select your database.

  1. On the Overview page, select Connect.

  1. In the Connect using a driver section, click your preferred language from the list to load language-specific instructions.

    If you have multiple regions, select the region you want to connect to from the dropdown menu for instructions.

Note, though, that the bundle URL is the same for all languages.

  1. Click Download Bundle.

    If you have multiple regions, you will have the option to download a bundle for each region from the expanded Download Bundle drop-down menu.

If you’ve enabled VPC peering, you can also Download External Secure Connect Bundle for use within your VPC peering. The secure-connect-database_name.zip file downloads, which contains the security certificates and credentials for your database.

VPC peering is only available on Classic databases.

Alternatively, you can right-click the Download credentials link, copy the link source, and then use a curl command to download the secure-connect-database_name.zip file:

curl -L "<secure-connect-database_name-download-URL>" > database_name.zip

Sharing secure connect bundle

Although teammates can access your Astra DB database, it will not display in their list of available databases under My Databases in the Astra DB console.

After you create an Astra DB database, you can grant access to other members of your team by providing them with the database credentials and connection details for your database.

Be careful when sharing connection details. Providing this information to another user grants them access to your Astra DB database and ownership capabilities, such as making modifications to the database.

For security, delete downloaded connection credentials after sending them to your teammate.

Collect Astra DB connection information

  1. From the secure connect bundle, collect the SSL related files:

    • ca.cert

    • cert

    • key

  2. From the cqlshrc file, collect the port.

Use only the port from cqlshrc. Other ports found in the secure connect bundle will not allow you to connect with this method.

  1. From the config.json file, grab the hostname.

Java legacy driver versions

Connect to DataStax Astra DB from Java using a previous version of the DataStax Driver. Before proceeding please consider upgrading to the most current driver if possible. However, if you cannot upgrade, or are using a Framework that doesn’t support Astra DB secure connect, the following instructions will help you get connected.

Prerequisites

  • Ensure the Java driver is installed. For more, see DataStax Java Driver.

  • include::manage:partial$collect_legacy_driver_info.adoc[]

  • Also collect the trustStore.jks and identity.jks from the secure connect bundle.

  • From the config.json in the secure connect bundle collect the keyStorePassword and trustStorePassword.

  • Client ID and Client Secret correspond to username and password. They are created when you generate your application token.

Procedure

  1. Copy the certificate files from the Astra DB secure connect bundle to ../secure-connect/. This folder should contain the trustStore.jks and identity.jks files.

  2. Replace the <hostname> with your Astra DB database hostname.

  3. Replace the <port> with your Astra DB database port.

  4. Replace <username> and <password> with the Astra DB database Client ID and Client Secret.

  5. Replace <keyStore pass> and <trustStore pass> with the values from the config.json.

Java 11
import com.datastax.driver.core.RemoteEndpointAwareJdkSSLOptions;
import com.datastax.driver.core.SSLOptions;
import org.springframework.data.cassandra.config.CassandraClusterFactoryBean;

import javax.net.ssl.*;
import java.io.File;
import java.security.KeyStore;
import java.security.SecureRandom;

public class Test {
    private static final String KEYSTORE_PATH = "../secure-connect/identity.jks";
    private static final char[] KEYSTORE_PASSWORD = "<keystore pass>".toCharArray();
    private static final String TRUSTSTORE_PATH = "../secure-connect/trustStore.jks";
    private static final char[] TRUSTSTORE_PASSWORD ="<trustStore pass>".toCharArray();
    private static final String contactPoints = "<hostname>";
    private static final int port = <port>;
    private static final boolean sslEnabled = true;
    private static final String username = "<clientId>";
    private static final String password = "<clientSecret>";

    @Override
    public CassandraClusterFactoryBean cluster(){

        CassandraClusterFactoryBean cluster = new CassandraClusterFactoryBean();

        cluster.setJmxReportingEnabled(false);
        cluster.setContactPoints(contactPoints);
        cluster.setPort(port);
        cluster.setSslEnabled(sslEnabled);
        cluster.setContactPoints(contactPoints);
        cluster.setUsername(username);
        cluster.setPassword(password);
        cluster.setSslOptions(generateSSLConf());

        return cluster;
    }
    public SSLOptions generateSSLConf() {
        try {
            KeyManagerFactory kmf;
            try {
                kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
                kmf.init(KeyStore.getInstance(KEYSTORE_PATH), KEYSTORE_PASSWORD);
            } catch (Exception e) {
                throw new RuntimeException("Unable to init KeyManagerFactory. Please check password and location.", e);
            }

            KeyStore truststore;
            try {
                truststore = KeyStore.getInstance(new File(TRUSTSTORE_PATH),TRUSTSTORE_PASSWORD);
            } catch (Exception e) {
                throw new RuntimeException("Unable to load the truststore. Check path and password.", e);
            }
            TrustManagerFactory tmf;
            try {
                tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
                tmf.init(truststore);
            } catch (Exception e) {
                throw new RuntimeException("Unable to init TrustManagerFactory.", e);
            }

            try {
                SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
                sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
                return RemoteEndpointAwareJdkSSLOptions.builder()
                        .withSSLContext(sslContext)
                        .build();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } catch (Throwable th) {
            throw new RuntimeException("Failed to load truststore for casandra", th);
        }
    }
}

Example

import com.datastax.driver.core.RemoteEndpointAwareJdkSSLOptions;
import com.datastax.driver.core.SSLOptions;
import org.springframework.data.cassandra.config.CassandraClusterFactoryBean;

import javax.net.ssl.*;
import java.io.File;
import java.security.KeyStore;
import java.security.SecureRandom;

public class Test {
    private static final String KEYSTORE_PATH = "../secure-connect/identity.jks";
    private static final char[] KEYSTORE_PASSWORD = "7cU6YS5jHbh8a".toCharArray();
    private static final String TRUSTSTORE_PATH = "../secure-connect/trustStore.jks";
    private static final char[] TRUSTSTORE_PASSWORD = "Dwp6KMa2lRd01".toCharArray();
    private static final String contactPoints = "7bb9cd7a-e49d-49a6-aa3d-be4878f974ef-us-east1.db.astra.datastax.com";
    private static final int port = 31575;
    private static final boolean sslEnabled = true;
    private static final String username = "john.smith";
    private static final String password = "jsP@ssw0rd";

    @Override
    public CassandraClusterFactoryBean cluster(){

        CassandraClusterFactoryBean cluster = new CassandraClusterFactoryBean();

        cluster.setJmxReportingEnabled(false);
        cluster.setContactPoints(contactPoints);
        cluster.setPort(port);
        cluster.setSslEnabled(sslEnabled);
        cluster.setContactPoints(contactPoints);
        cluster.setUsername(username);
        cluster.setPassword(password);
        cluster.setSslOptions(generateSSLConf());

        return cluster;
    }
    public SSLOptions generateSSLConf() {
        try {
            KeyManagerFactory kmf;
            try {
                kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
                kmf.init(KeyStore.getInstance(KEYSTORE_PATH), KEYSTORE_PASSWORD);
            } catch (Exception e) {
                throw new RuntimeException("Unable to init KeyManagerFactory. Please check password and location.", e);
            }

            KeyStore truststore;
            try {
                truststore = KeyStore.getInstance(new File(TRUSTSTORE_PATH),TRUSTSTORE_PASSWORD);
            } catch (Exception e) {
                throw new RuntimeException("Unable to load the truststore. Check path and password.", e);
            }
            TrustManagerFactory tmf;
            try {
                tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
                tmf.init(truststore);
            } catch (Exception e) {
                throw new RuntimeException("Unable to init TrustManagerFactory.", e);
            }

            try {
                SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
                sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
                return RemoteEndpointAwareJdkSSLOptions.builder()
                        .withSSLContext(sslContext)
                        .build();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } catch (Throwable th) {
            throw new RuntimeException("Failed to load truststore for casandra", th);
        }
    }
}

In the example above, the following variables are used:

  • hostname is 7bb9cd7a-e49d-49a6-aa3d-be4878f974ef-us-east1.db.astra.datastax.com

  • port is 31575

  • username is john.smith

  • password is jsP@ssw0rd

  • trustStore pass is Dwp6KMa2lRd01

  • keystore pass is 7cU6YS5jHbh8a

PHP legacy drivers

This example can be used to attach to Astra DB from PHP using the DataStax Driver. Before proceeding you might also consider using the REST, GraphQL or Document APIs to connect to Astra DB without the need for a custom driver.

Prerequisites

Procedure

  1. Copy the certificate files from the Astra DB secure connect bundle to /etc/ssl/certs/astra-secure-connect. This folder should contain the ca.cert, cert, and key files.

  2. Replace the <hostname> with your Astra DB database hostname.

  3. Replace the <port> with your Astra DB database port.

  4. Replace <username> and <password> with the Astra DB database Client ID and Client Secret.

<?php

$ssl     = Cassandra::ssl()
               \->withTrustedCerts('/etc/ssl/certs/astra-secure-connect/ca.cert')
               \->withClientCert('/etc/ssl/certs/astra-secure-connect/cert')
               \->withPrivateKey('/etc/ssl/certs/astra-secure-connect/key')
               \->build();


$cluster = Cassandra::cluster()
               \->withSSL($ssl)
               \->withCredentials("dbadmin", "my_awesome_password")
               \->withContactPoints('602c8f3c-ea96-41b0-a7c1-6c6c5bdd1f34-us-east1.db.astra.datastax.com')
               \->withPort(31575)
               \->build();

$session = $cluster\->connect();

$result = $session\->execute('SELECT keyspace_name, table_name FROM system_schema.tables');

foreach ($result as $row) {
    printf("The keyspace "%s" has a table "%s".
    ", $row['keyspace_name'], $row['table_name']);
}"

Example

<?php

$ssl     = Cassandra::ssl()
               \->withTrustedCerts('/etc/ssl/certs/astra-secure-connect/ca.cert')
               \->withClientCert('/etc/ssl/certs/astra-secure-connect/cert')
               \->withPrivateKey('/etc/ssl/certs/astra-secure-connect/key')
               \->build();

$cluster = Cassandra::cluster()
               \->withSSL($ssl)
               \->withCredentials("john.smith", "jsP@ssw0rd")
               \->withContactPoints('602c8f3c-ea96-41b0-a7c1-6c6c5bdd1f34-us-east1.db.astra.datastax.com')
               \->withPort(31575)
               \->build();
$session = $cluster\->connect();

$result = $session\->execute('SELECT keyspace_name, table_name FROM system_schema.tables');

foreach ($result as $row) {
    printf("The keyspace "%s" has a table "%s".
    ", $row['keyspace_name'], $row['table_name']);
    }"

In the example above, the following variables are used:

  • <hostname> is 602c8f3c-ea96-41b0-a7c1-6c6c5bdd1f34-us-east1.db.astra.datastax.com

  • <port> is 31575

  • <username> is john.smith

  • <password> is jsP@ssw0rd

Python legacy driver versions

Connect to Astra DB from Python using a previous version of the DataStax Driver. Before proceeding please consider upgrading to the most current driver if possible. However, if you cannot upgrade, or are using a Framework that doesn’t support Astra DB secure connect, the following instructions will help you get connected.

Prerequisites

Procedure

  1. Copy the certificate files from the Astra DB secure connect bundle to ../secure-connect/.

    This folder should contain the ca.cert, cert, and key files.

  2. Replace the <hostname> with your Astra DB database hostname.

  3. Replace the <port> with your Astra DB database port.

  4. Replace <username> and <password> with the Astra DB database Client ID and Client Secret.

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

ssl_context = SSLContext(PROTOCOL_TLSv1)
ssl_context.load_verify_locations('../secure-connect/ca.crt')
ssl_context.verify_mode = CERT_REQUIRED
ssl_context.load_cert_chain(
    certfile='../secure-connect/cert',
    keyfile='../secure-connect/key')


auth_provider = PlainTextAuthProvider('<username>', '<password>')
cluster = Cluster(['<hostname>'], port=<port>, ssl_context=ssl_context, auth_provider=auth_provider)
session = cluster.connect()

row = session.execute("select release_version from system.local").one()
if row:
  print(row[0])
else:
  print("An error occurred.")


print(cluster.metadata.keyspaces)

Example

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

ssl_context = SSLContext(PROTOCOL_TLSv1)
ssl_context.load_verify_locations('../secure-connect/ca.crt')
ssl_context.verify_mode = CERT_REQUIRED
ssl_context.load_cert_chain(
    certfile='../secure-connect/cert',
    keyfile='../secure-connect/key')


auth_provider = PlainTextAuthProvider('john.smith', 'jsP@ssw0rd')
cluster = Cluster(['7bb9cd7a-e49d-49a6-aa3d-be4878f974ef-us-east1.db.astra.datastax.com'], port=31575, ssl_context=ssl_context, auth_provider=auth_provider)
session = cluster.connect()

row = session.execute("select release_version from system.local").one()
if row:
  print(row[0])
else:
  print("An error occurred.")


print(cluster.metadata.keyspaces)

In the example above, the following variables are used:

  • hostname is 7bb9cd7a-e49d-49a6-aa3d-be4878f974ef-us-east1.db.astra.datastax.com

  • port is 31575

  • username is john.smith

  • password is jsP@ssw0rd

Flask CQLAlchemy framework

Following the procedure above this code allows CQLAlchemy to utilize Astra DB.

import uuid
from flask import Flask
from flask_cqlalchemy import CQLAlchemy
from ssl import SSLContext, PROTOCOL_TLS, CERT_REQUIRED
from cassandra.auth import PlainTextAuthProvider


auth_provider = PlainTextAuthProvider(username='<username>', password='<password>')
ssl_context = SSLContext(PROTOCOL_TLSv1)
ssl_context.load_verify_locations("../secure-connect/ca.crt")
ssl_context.verify_mode = CERT_REQUIRED
ssl_context.load_cert_chain(
  certfile="../secure-connect/cert",
  keyfile="secure-connect/key")

app = Flask(__name__)
app.config['CASSANDRA_HOSTS'] = ['<hostname>']
app.config['CASSANDRA_SETUP_KWARGS'] = dict(ssl_context=ssl_context, port="<port>", auth_provider=auth_provider)
app.config['CASSANDRA_KEYSPACE'] = "cqlengine"
db = CQLAlchemy(app)


class User(db.Model):
    uid = db.columns.UUID(primary_key=True, default=uuid.uuid4)
    username = db.columns.Text(required=False)
Example
import uuid
from flask import Flask
from flask_cqlalchemy import CQLAlchemy
from ssl import SSLContext, PROTOCOL_TLS, CERT_REQUIRED
from cassandra.auth import PlainTextAuthProvider


auth_provider = PlainTextAuthProvider(username='jane.smith', password='jsP@ssw0rd')
ssl_context = SSLContext(PROTOCOL_TLSv1)
ssl_context.load_verify_locations("../secure-connect/ca.crt")
ssl_context.verify_mode = CERT_REQUIRED
ssl_context.load_cert_chain(
  certfile="../secure-connect/cert",
  keyfile="secure-connect/key")

app = Flask(__name__)
app.config['CASSANDRA_HOSTS'] = ['7bb9cd7a-e49d-49a6-aa3d-be4878f974ef-us-east1.db.astra.datastax.com']
app.config['CASSANDRA_SETUP_KWARGS'] = dict(ssl_context=ssl_context, port="31575", auth_provider=auth_provider)
app.config['CASSANDRA_KEYSPACE'] = "cqlengine"
db = CQLAlchemy(app)


class User(db.Model):
    uid = db.columns.UUID(primary_key=True, default=uuid.uuid4)
    username = db.columns.Text(required=False)

Ruby legacy drivers

This example can be used to attach to DataStax Astra DB from Ruby using the DataStax Driver. Before proceeding you might also consider using the REST, GraphQL or Document APIs to connect to Astra DB without the need for a custom driver.

Prerequisites

Procedure

  1. Copy the certificate files from the Astra DB secure connect bundle to /etc/ssl/certs/astra-secure-connect. This folder should contain the ca.cert, cert, and key files.

  1. Replace the <hostname> with your Astra DB database hostname.

  1. Replace the <port> with your Astra DB database port.

  1. Replace <username> and <password> with the Astra DB database Client ID and Client Secret.

require 'cassandra'

cluster = Cassandra.cluster(
            username: '<username>',
            password: '<password>',
            hosts: ['<hostname>'],
            port: <port>,
            server_cert: '/etc/ssl/certs/astra-secure-connect/ca.cert',
            client_cert: '/etc/ssl/certs/astra-secure-connect/cert',
            private_key: '/etc/ssl/certs/astra-secure-connect/key'
)

keyspace = 'system_schema'
session  = cluster.connect(keyspace) # create session, optionally scoped to a keyspace, to execute queries

future = session.execute_async('SELECT keyspace_name, table_name FROM tables') # fully asynchronous api
future.on_success do |rows|
  rows.each do |row|
    puts "The keyspace #{row['keyspace_name']} has a table #{row['table_name']}"
  end
end
future.join

Example

require 'cassandra'

cluster = Cassandra.cluster(
            username: 'john.smith',
            password: 'jsP@ssw0rd',
            hosts: ['602c8f3c-ea96-41b0-a7c1-6c6c5bdd1f34-us-east1.db.astra.datastax.com'],
            port: 31575,
            server_cert: '/etc/ssl/certs/astra-secure-connect/ca.cert',
            client_cert: '/etc/ssl/certs/astra-secure-connect/cert',
            private_key: '/etc/ssl/certs/astra-secure-connect/key'
)

keyspace = 'system_schema'
session  = cluster.connect(keyspace) # create session, optionally scoped to a keyspace, to execute queries

future = session.execute_async('SELECT keyspace_name, table_name FROM tables') # fully asynchronous api
future.on_success do |rows|
  rows.each do |row|
    puts "The keyspace #{row['keyspace_name']} has a table #{row['table_name']}"
  end
end
future.join

In the example above, the following variables are used:

  • hostname is 602c8f3c-ea96-41b0-a7c1-6c6c5bdd1f34-us-east1.db.astra.datastax.com

  • port is 31575

  • username is john.smith

  • password is jsP@ssw0rd