Create a cluster - Amazon Aurora DSQL

Create a cluster

See the following information to learn how to create single-Region and multi-Region clusters in Aurora DSQL.

Python

To create a cluster in a single AWS Region, use the following example.

import boto3 def create_cluster(region): try: client = boto3.client("dsql", region_name=region) tags = {"Name": "Python single region cluster"} cluster = client.create_cluster(tags=tags, deletionProtectionEnabled=True) print(f"Initiated creation of cluster: {cluster["identifier"]}") print(f"Waiting for {cluster["arn"]} to become ACTIVE") client.get_waiter("cluster_active").wait( identifier=cluster["identifier"], WaiterConfig={ 'Delay': 10, 'MaxAttempts': 30 } ) return cluster except: print("Unable to create cluster") raise def main(): region = "us-east-1" response = create_cluster(region) print(f"Created cluster: {response["arn"]}") if __name__ == "__main__": main()

To create a multi-Region cluster, use the following example. Creating a multi-Region cluster might take some time.

import boto3 def create_multi_region_clusters(region_1, region_2, witness_region): try: client_1 = boto3.client("dsql", region_name=region_1) client_2 = boto3.client("dsql", region_name=region_2) # We can only set the witness region for the first cluster cluster_1 = client_1.create_cluster( deletionProtectionEnabled=True, multiRegionProperties={"witnessRegion": witness_region}, tags={"Name": "Python multi region cluster"} ) print(f"Created {cluster_1["arn"]}") # For the second cluster we can set witness region and designate cluster_1 as a peer cluster_2 = client_2.create_cluster( deletionProtectionEnabled=True, multiRegionProperties={"witnessRegion": witness_region, "clusters": [cluster_1["arn"]]}, tags={"Name": "Python multi region cluster"} ) print(f"Created {cluster_2["arn"]}") # Now that we know the cluster_2 arn we can set it as a peer of cluster_1 client_1.update_cluster( identifier=cluster_1["identifier"], multiRegionProperties={"witnessRegion": witness_region, "clusters": [cluster_2["arn"]]} ) print(f"Added {cluster_2["arn"]} as a peer of {cluster_1["arn"]}") # Now that multiRegionProperties is fully defined for both clusters # they'll begin the transition to ACTIVE print(f"Waiting for {cluster_1["arn"]} to become ACTIVE") client_1.get_waiter("cluster_active").wait( identifier=cluster_1["identifier"], WaiterConfig={ 'Delay': 10, 'MaxAttempts': 30 } ) print(f"Waiting for {cluster_2["arn"]} to become ACTIVE") client_2.get_waiter("cluster_active").wait( identifier=cluster_2["identifier"], WaiterConfig={ 'Delay': 10, 'MaxAttempts': 30 } ) return (cluster_1, cluster_2) except: print("Unable to create cluster") raise def main(): region_1 = "us-east-1" region_2 = "us-east-2" witness_region = "us-west-2" (cluster_1, cluster_2) = create_multi_region_clusters(region_1, region_2, witness_region) print("Created multi region clusters:") print("Cluster id: " + cluster_1['arn']) print("Cluster id: " + cluster_2['arn']) if __name__ == "__main__": main()
C++

The following example lets you create a cluster in a single AWS Region.

#include <aws/core/Aws.h> #include <aws/core/utils/Outcome.h> #include <aws/dsql/DSQLClient.h> #include <aws/dsql/model/CreateClusterRequest.h> #include <aws/dsql/model/GetClusterRequest.h> #include <iostream> #include <thread> #include <chrono> using namespace Aws; using namespace Aws::DSQL; using namespace Aws::DSQL::Model; /** * Creates a single-region cluster in Amazon Aurora DSQL */ CreateClusterResult CreateCluster(const Aws::String& region) { // Create client for the specified region DSQL::DSQLClientConfiguration clientConfig; clientConfig.region = region; DSQL::DSQLClient client(clientConfig); // Create the cluster CreateClusterRequest createClusterRequest; createClusterRequest.SetDeletionProtectionEnabled(true); createClusterRequest.SetClientToken(Aws::Utils::UUID::RandomUUID()); // Add tags Aws::Map<Aws::String, Aws::String> tags; tags["Name"] = "cpp single region cluster"; createClusterRequest.SetTags(tags); auto createOutcome = client.CreateCluster(createClusterRequest); if (!createOutcome.IsSuccess()) { std::cerr << "Failed to create cluster in " << region << ": " << createOutcome.GetError().GetMessage() << std::endl; throw std::runtime_error("Unable to create cluster in " + region); } auto cluster = createOutcome.GetResult(); std::cout << "Created " << cluster.GetArn() << std::endl; return cluster; } int main() { Aws::SDKOptions options; Aws::InitAPI(options); { try { // Define region for the single-region setup Aws::String region = "us-east-1"; auto cluster = CreateCluster(region); std::cout << "Created single region cluster:" << std::endl; std::cout << "Cluster ARN: " << cluster.GetArn() << std::endl; std::cout << "Cluster Status: " << ClusterStatusMapper::GetNameForClusterStatus(cluster.GetStatus()) << std::endl; } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; } } Aws::ShutdownAPI(options); return 0; }

To create a multi-Region cluster, use the following example. Creating a multi-Region cluster might take some time.

#include <aws/core/Aws.h> #include <aws/core/utils/Outcome.h> #include <aws/dsql/DSQLClient.h> #include <aws/dsql/model/CreateClusterRequest.h> #include <aws/dsql/model/UpdateClusterRequest.h> #include <aws/dsql/model/MultiRegionProperties.h> #include <aws/dsql/model/GetClusterRequest.h> #include <iostream> #include <thread> #include <chrono> using namespace Aws; using namespace Aws::DSQL; using namespace Aws::DSQL::Model; /** * Creates multi-region clusters in Amazon Aurora DSQL */ std::pair<CreateClusterResult, CreateClusterResult> CreateMultiRegionClusters( const Aws::String& region1, const Aws::String& region2, const Aws::String& witnessRegion) { // Create clients for each region DSQL::DSQLClientConfiguration clientConfig1; clientConfig1.region = region1; DSQL::DSQLClient client1(clientConfig1); DSQL::DSQLClientConfiguration clientConfig2; clientConfig2.region = region2; DSQL::DSQLClient client2(clientConfig2); // We can only set the witness region for the first cluster std::cout << "Creating cluster in " << region1 << std::endl; CreateClusterRequest createClusterRequest1; createClusterRequest1.SetDeletionProtectionEnabled(true); // Set multi-region properties with witness region MultiRegionProperties multiRegionProps1; multiRegionProps1.SetWitnessRegion(witnessRegion); createClusterRequest1.SetMultiRegionProperties(multiRegionProps1); // Add tags Aws::Map<Aws::String, Aws::String> tags; tags["Name"] = "cpp multi region cluster 1"; createClusterRequest1.SetTags(tags); createClusterRequest1.SetClientToken(Aws::Utils::UUID::RandomUUID()); auto createOutcome1 = client1.CreateCluster(createClusterRequest1); if (!createOutcome1.IsSuccess()) { std::cerr << "Failed to create cluster in " << region1 << ": " << createOutcome1.GetError().GetMessage() << std::endl; throw std::runtime_error("Failed to create multi-region clusters"); } auto cluster1 = createOutcome1.GetResult(); std::cout << "Created " << cluster1.GetArn() << std::endl; // For the second cluster we can set witness region and designate cluster1 as a peer std::cout << "Creating cluster in " << region2 << std::endl; CreateClusterRequest createClusterRequest2; createClusterRequest2.SetDeletionProtectionEnabled(true); // Set multi-region properties with witness region and cluster1 as peer MultiRegionProperties multiRegionProps2; multiRegionProps2.SetWitnessRegion(witnessRegion); Aws::Vector<Aws::String> clusters; clusters.push_back(cluster1.GetArn()); multiRegionProps2.SetClusters(clusters); tags["Name"] = "cpp multi region cluster 2"; createClusterRequest2.SetMultiRegionProperties(multiRegionProps2); createClusterRequest2.SetTags(tags); createClusterRequest2.SetClientToken(Aws::Utils::UUID::RandomUUID()); auto createOutcome2 = client2.CreateCluster(createClusterRequest2); if (!createOutcome2.IsSuccess()) { std::cerr << "Failed to create cluster in " << region2 << ": " << createOutcome2.GetError().GetMessage() << std::endl; throw std::runtime_error("Failed to create multi-region clusters"); } auto cluster2 = createOutcome2.GetResult(); std::cout << "Created " << cluster2.GetArn() << std::endl; // Now that we know the cluster2 arn we can set it as a peer of cluster1 UpdateClusterRequest updateClusterRequest; updateClusterRequest.SetIdentifier(cluster1.GetIdentifier()); MultiRegionProperties updatedProps; updatedProps.SetWitnessRegion(witnessRegion); Aws::Vector<Aws::String> updatedClusters; updatedClusters.push_back(cluster2.GetArn()); updatedProps.SetClusters(updatedClusters); updateClusterRequest.SetMultiRegionProperties(updatedProps); updateClusterRequest.SetClientToken(Aws::Utils::UUID::RandomUUID()); auto updateOutcome = client1.UpdateCluster(updateClusterRequest); if (!updateOutcome.IsSuccess()) { std::cerr << "Failed to update cluster in " << region1 << ": " << updateOutcome.GetError().GetMessage() << std::endl; throw std::runtime_error("Failed to update multi-region clusters"); } std::cout << "Added " << cluster2.GetArn() << " as a peer of " << cluster1.GetArn() << std::endl; return std::make_pair(cluster1, cluster2); } int main() { Aws::SDKOptions options; Aws::InitAPI(options); { try { // Define regions for the multi-region setup Aws::String region1 = "us-east-1"; Aws::String region2 = "us-east-2"; Aws::String witnessRegion = "us-west-2"; auto [cluster1, cluster2] = CreateMultiRegionClusters(region1, region2, witnessRegion); std::cout << "Created multi region clusters:" << std::endl; std::cout << "Cluster 1 ARN: " << cluster1.GetArn() << std::endl; std::cout << "Cluster 2 ARN: " << cluster2.GetArn() << std::endl; } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; } } Aws::ShutdownAPI(options); return 0; }
JavaScript

To create a cluster in a single AWS Region, use the following example.

import { DSQLClient, CreateClusterCommand, waitUntilClusterActive } from "@aws-sdk/client-dsql"; async function createCluster(region) { const client = new DSQLClient({ region }); try { const createClusterCommand = new CreateClusterCommand({ deletionProtectionEnabled: true, tags: { Name: "javascript single region cluster" }, }); const response = await client.send(createClusterCommand); console.log(`Waiting for cluster ${response.identifier} to become ACTIVE`); await waitUntilClusterActive( { client: client, maxWaitTime: 300 // Wait for 5 minutes }, { identifier: response.identifier } ); console.log(`Cluster Id ${response.identifier} is now active`); return; } catch (error) { console.error(`Unable to create cluster in ${region}: `, error.message); throw error; } } async function main() { const region = "us-east-1"; await createCluster(region); } main();

To create a multi-Region cluster, use the following example. Creating a multi-Region cluster might take some time.

import { DSQLClient, CreateClusterCommand, UpdateClusterCommand, waitUntilClusterActive } from "@aws-sdk/client-dsql"; async function createMultiRegionCluster(region1, region2, witnessRegion) { const client1 = new DSQLClient({ region: region1 }); const client2 = new DSQLClient({ region: region2 }); try { // We can only set the witness region for the first cluster console.log(`Creating cluster in ${region1}`); const createClusterCommand1 = new CreateClusterCommand({ deletionProtectionEnabled: true, tags: { Name: "javascript multi region cluster 1" }, multiRegionProperties: { witnessRegion: witnessRegion } }); const response1 = await client1.send(createClusterCommand1); console.log(`Created ${response1.arn}`); // For the second cluster we can set witness region and designate the first cluster as a peer console.log(`Creating cluster in ${region2}`); const createClusterCommand2 = new CreateClusterCommand({ deletionProtectionEnabled: true, tags: { Name: "javascript multi region cluster 2" }, multiRegionProperties: { witnessRegion: witnessRegion, clusters: [response1.arn] } }); const response2 = await client2.send(createClusterCommand2); console.log(`Created ${response2.arn}`); // Now that we know the second cluster arn we can set it as a peer of the first cluster const updateClusterCommand1 = new UpdateClusterCommand( { identifier: response1.identifier, multiRegionProperties: { witnessRegion: witnessRegion, clusters: [response2.arn] } } ); await client1.send(updateClusterCommand1); console.log(`Added ${response2.arn} as a peer of ${response1.arn}`); // Now that multiRegionProperties is fully defined for both clusters // they'll begin the transition to ACTIVE console.log(`Waiting for cluster 1 ${response1.identifier} to become ACTIVE`); await waitUntilClusterActive( { client: client1, maxWaitTime: 300 // Wait for 5 minutes }, { identifier: response1.identifier } ); console.log(`Cluster 1 is now active`); console.log(`Waiting for cluster 2 ${response2.identifier} to become ACTIVE`); await waitUntilClusterActive( { client: client2, maxWaitTime: 300 // Wait for 5 minutes }, { identifier: response2.identifier } ); console.log(`Cluster 2 is now active`); console.log("The multi region clusters are now active"); return; } catch (error) { console.error("Failed to create cluster: ", error.message); throw error; } } async function main() { const region1 = "us-east-1"; const region2 = "us-east-2"; const witnessRegion = "us-west-2"; await createMultiRegionCluster(region1, region2, witnessRegion); } main();
Java

Use the following example to create a cluster in a single AWS Region.

package org.example; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.core.waiters.WaiterResponse; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.retries.api.BackoffStrategy; import software.amazon.awssdk.services.dsql.DsqlClient; import software.amazon.awssdk.services.dsql.model.CreateClusterRequest; import software.amazon.awssdk.services.dsql.model.CreateClusterResponse; import software.amazon.awssdk.services.dsql.model.GetClusterResponse; import java.time.Duration; import java.util.Map; public class CreateCluster { public static void main(String[] args) { Region region = Region.US_EAST_1; try ( DsqlClient client = DsqlClient.builder() .region(region) .credentialsProvider(DefaultCredentialsProvider.create()) .build() ) { CreateClusterRequest request = CreateClusterRequest.builder() .deletionProtectionEnabled(true) .tags(Map.of("Name", "java single region cluster")) .build(); CreateClusterResponse cluster = client.createCluster(request); System.out.println("Created " + cluster.arn()); // The DSQL SDK offers a built-in waiter to poll for a cluster's // transition to ACTIVE. System.out.println("Waiting for cluster to become ACTIVE"); WaiterResponse<GetClusterResponse> waiterResponse = client.waiter().waitUntilClusterActive( getCluster -> getCluster.identifier(cluster.identifier()), config -> config.backoffStrategyV2( BackoffStrategy.fixedDelayWithoutJitter(Duration.ofSeconds(10)) ).waitTimeout(Duration.ofMinutes(5)) ); waiterResponse.matched().response().ifPresent(System.out::println); } } }

To create a multi-Region cluster, use the following example. Creating a multi-Region cluster might take some time.

package org.example; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.retries.api.BackoffStrategy; import software.amazon.awssdk.services.dsql.DsqlClient; import software.amazon.awssdk.services.dsql.DsqlClientBuilder; import software.amazon.awssdk.services.dsql.model.CreateClusterRequest; import software.amazon.awssdk.services.dsql.model.CreateClusterResponse; import software.amazon.awssdk.services.dsql.model.GetClusterResponse; import software.amazon.awssdk.services.dsql.model.UpdateClusterRequest; import java.time.Duration; import java.util.Map; public class CreateMultiRegionCluster { public static void main(String[] args) { Region region1 = Region.US_EAST_1; Region region2 = Region.US_EAST_2; Region witnessRegion = Region.US_WEST_2; DsqlClientBuilder clientBuilder = DsqlClient.builder() .credentialsProvider(DefaultCredentialsProvider.create()); try ( DsqlClient client1 = clientBuilder.region(region1).build(); DsqlClient client2 = clientBuilder.region(region2).build() ) { // We can only set the witness region for the first cluster System.out.println("Creating cluster in " + region1); CreateClusterRequest request1 = CreateClusterRequest.builder() .deletionProtectionEnabled(true) .multiRegionProperties(mrp -> mrp.witnessRegion(witnessRegion.toString())) .tags(Map.of("Name", "java multi region cluster")) .build(); CreateClusterResponse cluster1 = client1.createCluster(request1); System.out.println("Created " + cluster1.arn()); // For the second cluster we can set the witness region and designate // cluster1 as a peer. System.out.println("Creating cluster in " + region2); CreateClusterRequest request2 = CreateClusterRequest.builder() .deletionProtectionEnabled(true) .multiRegionProperties(mrp -> mrp.witnessRegion(witnessRegion.toString()).clusters(cluster1.arn()) ) .tags(Map.of("Name", "java multi region cluster")) .build(); CreateClusterResponse cluster2 = client2.createCluster(request2); System.out.println("Created " + cluster2.arn()); // Now that we know the cluster2 ARN we can set it as a peer of cluster1 UpdateClusterRequest updateReq = UpdateClusterRequest.builder() .identifier(cluster1.identifier()) .multiRegionProperties(mrp -> mrp.witnessRegion(witnessRegion.toString()).clusters(cluster2.arn()) ) .build(); client1.updateCluster(updateReq); System.out.printf("Added %s as a peer of %s%n", cluster2.arn(), cluster1.arn()); // Now that MultiRegionProperties is fully defined for both clusters they'll begin // the transition to ACTIVE. System.out.printf("Waiting for cluster %s to become ACTIVE%n", cluster1.arn()); GetClusterResponse activeCluster1 = client1.waiter().waitUntilClusterActive( getCluster -> getCluster.identifier(cluster1.identifier()), config -> config.backoffStrategyV2( BackoffStrategy.fixedDelayWithoutJitter(Duration.ofSeconds(10)) ).waitTimeout(Duration.ofMinutes(5)) ).matched().response().orElseThrow(); System.out.printf("Waiting for cluster %s to become ACTIVE%n", cluster2.arn()); GetClusterResponse activeCluster2 = client2.waiter().waitUntilClusterActive( getCluster -> getCluster.identifier(cluster2.identifier()), config -> config.backoffStrategyV2( BackoffStrategy.fixedDelayWithoutJitter(Duration.ofSeconds(10)) ).waitTimeout(Duration.ofMinutes(5)) ).matched().response().orElseThrow(); System.out.println("Created multi region clusters:"); System.out.println(activeCluster1); System.out.println(activeCluster2); } } }
Rust

Use the following example to create a cluster in a single AWS Region.

use aws_config::load_defaults; use aws_sdk_dsql::client::Waiters; use aws_sdk_dsql::operation::get_cluster::GetClusterOutput; use aws_sdk_dsql::{ Client, Config, config::{BehaviorVersion, Region}, }; use std::collections::HashMap; /// Create a client. We will use this later for performing operations on the cluster. async fn dsql_client(region: &'static str) -> Client { // Load default SDK configuration let sdk_defaults = load_defaults(BehaviorVersion::latest()).await; // You can set your own credentials by following this guide // https://docs.aws.amazon.com/sdk-for-rust/latest/dg/credproviders.html let credentials = sdk_defaults.credentials_provider().unwrap(); let config = Config::builder() .behavior_version(BehaviorVersion::latest()) .credentials_provider(credentials) .region(Region::new(region)) .build(); Client::from_conf(config) } /// Create a cluster without delete protection and a name pub async fn create_cluster(region: &'static str) -> GetClusterOutput { let client = dsql_client(region).await; let tags = HashMap::from([( String::from("Name"), String::from("rust single region cluster"), )]); let create_cluster_output = client .create_cluster() .set_tags(Some(tags)) .deletion_protection_enabled(true) .send() .await .unwrap(); println!("Created {}", create_cluster_output.arn); println!("Waiting for cluster to become ACTIVE"); client .wait_until_cluster_active() .identifier(&create_cluster_output.identifier) .wait(std::time::Duration::from_secs(300)) // Wait up to 5 minutes .await .unwrap() .into_result() .unwrap() } #[tokio::main(flavor = "current_thread")] pub async fn main() -> anyhow::Result<()> { let region = "us-east-1"; let output = create_cluster(region).await; println!("{:#?}", output); Ok(()) }

To create a multi-Region cluster, use the following example. Creating a multi-Region cluster might take some time.

use aws_config::{BehaviorVersion, Region, load_defaults}; use aws_sdk_dsql::client::Waiters; use aws_sdk_dsql::operation::get_cluster::GetClusterOutput; use aws_sdk_dsql::types::MultiRegionProperties; use aws_sdk_dsql::{Client, Config}; use std::collections::HashMap; /// Create a client. We will use this later for performing operations on the cluster. async fn dsql_client(region: &'static str) -> Client { // Load default SDK configuration let sdk_defaults = load_defaults(BehaviorVersion::latest()).await; // You can set your own credentials by following this guide // https://docs.aws.amazon.com/sdk-for-rust/latest/dg/credproviders.html let credentials = sdk_defaults.credentials_provider().unwrap(); let config = Config::builder() .behavior_version(BehaviorVersion::latest()) .credentials_provider(credentials) .region(Region::new(region)) .build(); Client::from_conf(config) } /// Create a cluster without delete protection and a name pub async fn create_multi_region_clusters( region_1: &'static str, region_2: &'static str, witness_region: &'static str, ) -> (GetClusterOutput, GetClusterOutput) { let client_1 = dsql_client(region_1).await; let client_2 = dsql_client(region_2).await; let tags = HashMap::from([( String::from("Name"), String::from("rust multi region cluster"), )]); // We can only set the witness region for the first cluster println!("Creating cluster in {region_1}"); let cluster_1 = client_1 .create_cluster() .set_tags(Some(tags.clone())) .deletion_protection_enabled(true) .multi_region_properties( MultiRegionProperties::builder() .witness_region(witness_region) .build(), ) .send() .await .unwrap(); let cluster_1_arn = &cluster_1.arn; println!("Created {cluster_1_arn}"); // For the second cluster we can set witness region and designate cluster_1 as a peer println!("Creating cluster in {region_2}"); let cluster_2 = client_2 .create_cluster() .set_tags(Some(tags)) .deletion_protection_enabled(true) .multi_region_properties( MultiRegionProperties::builder() .witness_region(witness_region) .clusters(&cluster_1.arn) .build(), ) .send() .await .unwrap(); let cluster_2_arn = &cluster_2.arn; println!("Created {cluster_2_arn}"); // Now that we know the cluster_2 arn we can set it as a peer of cluster_1 client_1 .update_cluster() .identifier(&cluster_1.identifier) .multi_region_properties( MultiRegionProperties::builder() .witness_region(witness_region) .clusters(&cluster_2.arn) .build(), ) .send() .await .unwrap(); println!("Added {cluster_2_arn} as a peer of {cluster_1_arn}"); // Now that the multi-region properties are fully defined for both clusters // they'll begin the transition to ACTIVE println!("Waiting for {cluster_1_arn} to become ACTIVE"); let cluster_1_output = client_1 .wait_until_cluster_active() .identifier(&cluster_1.identifier) .wait(std::time::Duration::from_secs(300)) // Wait up to 5 minutes .await .unwrap() .into_result() .unwrap(); println!("Waiting for {cluster_2_arn} to become ACTIVE"); let cluster_2_output = client_2 .wait_until_cluster_active() .identifier(&cluster_2.identifier) .wait(std::time::Duration::from_secs(300)) // Wait up to 5 minutes .await .unwrap() .into_result() .unwrap(); (cluster_1_output, cluster_2_output) } #[tokio::main(flavor = "current_thread")] pub async fn main() -> anyhow::Result<()> { let region_1 = "us-east-1"; let region_2 = "us-east-2"; let witness_region = "us-west-2"; let (cluster_1, cluster_2) = create_multi_region_clusters(region_1, region_2, witness_region).await; println!("Created multi region clusters:"); println!("{:#?}", cluster_1); println!("{:#?}", cluster_2); Ok(()) }
Ruby

Use the following example to create a cluster in a single AWS Region.

require "aws-sdk-dsql" require "pp" def create_cluster(region) client = Aws::DSQL::Client.new(region: region) cluster = client.create_cluster( deletion_protection_enabled: true, tags: { Name: "ruby single region cluster" } ) puts "Created #{cluster.arn}" # The DSQL SDK offers built-in waiters to poll for a cluster's # transition to ACTIVE. puts "Waiting for cluster to become ACTIVE" client.wait_until(:cluster_active, identifier: cluster.identifier) do |w| # Wait for 5 minutes w.max_attempts = 30 w.delay = 10 end rescue Aws::Errors::ServiceError => e abort "Unable to create cluster in #{region}: #{e.message}" end def main region = "us-east-1" cluster = create_cluster(region) pp cluster end main if $PROGRAM_NAME == __FILE__

To create a multi-Region cluster, use the following example. Creating a multi-Region cluster might take some time.

require "aws-sdk-dsql" require "pp" def create_multi_region_clusters(region_1, region_2, witness_region) client_1 = Aws::DSQL::Client.new(region: region_1) client_2 = Aws::DSQL::Client.new(region: region_2) # We can only set the witness region for the first cluster puts "Creating cluster in #{region_1}" cluster_1 = client_1.create_cluster( deletion_protection_enabled: true, multi_region_properties: { witness_region: witness_region }, tags: { Name: "ruby multi region cluster" } ) puts "Created #{cluster_1.arn}" # For the second cluster we can set witness region and designate cluster_1 as a peer puts "Creating cluster in #{region_2}" cluster_2 = client_2.create_cluster( deletion_protection_enabled: true, multi_region_properties: { witness_region: witness_region, clusters: [ cluster_1.arn ] }, tags: { Name: "ruby multi region cluster" } ) puts "Created #{cluster_2.arn}" # Now that we know the cluster_2 arn we can set it as a peer of cluster_1 client_1.update_cluster( identifier: cluster_1.identifier, multi_region_properties: { witness_region: witness_region, clusters: [ cluster_2.arn ] } ) puts "Added #{cluster_2.arn} as a peer of #{cluster_1.arn}" # Now that multi_region_properties is fully defined for both clusters # they'll begin the transition to ACTIVE puts "Waiting for #{cluster_1.arn} to become ACTIVE" cluster_1 = client_1.wait_until(:cluster_active, identifier: cluster_1.identifier) do |w| # Wait for 5 minutes w.max_attempts = 30 w.delay = 10 end puts "Waiting for #{cluster_2.arn} to become ACTIVE" cluster_2 = client_2.wait_until(:cluster_active, identifier: cluster_2.identifier) do |w| w.max_attempts = 30 w.delay = 10 end [ cluster_1, cluster_2 ] rescue Aws::Errors::ServiceError => e abort "Failed to create multi-region clusters: #{e.message}" end def main region_1 = "us-east-1" region_2 = "us-east-2" witness_region = "us-west-2" cluster_1, cluster_2 = create_multi_region_clusters(region_1, region_2, witness_region) puts "Created multi region clusters:" pp cluster_1 pp cluster_2 end main if $PROGRAM_NAME == __FILE__
.NET

Use the following example to create a cluster in a single AWS Region.

using System; using System.Collections.Generic; using System.Threading.Tasks; using Amazon; using Amazon.DSQL; using Amazon.DSQL.Model; using Amazon.Runtime.Credentials; namespace DSQLExamples.examples { public class CreateSingleRegionCluster { /// <summary> /// Create a client. We will use this later for performing operations on the cluster. /// </summary> private static async Task<AmazonDSQLClient> CreateDSQLClient(RegionEndpoint region) { var awsCredentials = await DefaultAWSCredentialsIdentityResolver.GetCredentialsAsync(); var clientConfig = new AmazonDSQLConfig { RegionEndpoint = region }; return new AmazonDSQLClient(awsCredentials, clientConfig); } /// <summary> /// Create a cluster without delete protection and a name. /// </summary> public static async Task<CreateClusterResponse> Create(RegionEndpoint region) { using (var client = await CreateDSQLClient(region)) { var tags = new Dictionary<string, string> { { "Name", "csharp single region cluster" } }; var createClusterRequest = new CreateClusterRequest { DeletionProtectionEnabled = true, Tags = tags }; CreateClusterResponse response = await client.CreateClusterAsync(createClusterRequest); Console.WriteLine($"Initiated creation of {response.Arn}"); return response; } } private static async Task Main() { var region = RegionEndpoint.USEast1; await Create(region); } } }

To create a multi-Region cluster, use the following example. Creating a multi-Region cluster might take some time.

using System; using System.Collections.Generic; using System.Threading.Tasks; using Amazon; using Amazon.DSQL; using Amazon.DSQL.Model; using Amazon.Runtime.Credentials; using Amazon.Runtime.Endpoints; namespace DSQLExamples.examples { public class CreateMultiRegionClusters { /// <summary> /// Create a client. We will use this later for performing operations on the cluster. /// </summary> private static async Task<AmazonDSQLClient> CreateDSQLClient(RegionEndpoint region) { var awsCredentials = await DefaultAWSCredentialsIdentityResolver.GetCredentialsAsync(); var clientConfig = new AmazonDSQLConfig { RegionEndpoint = region, }; return new AmazonDSQLClient(awsCredentials, clientConfig); } /// <summary> /// Create multi-region clusters with a witness region. /// </summary> public static async Task<(CreateClusterResponse, CreateClusterResponse)> Create( RegionEndpoint region1, RegionEndpoint region2, RegionEndpoint witnessRegion) { using (var client1 = await CreateDSQLClient(region1)) using (var client2 = await CreateDSQLClient(region2)) { var tags = new Dictionary<string, string> { { "Name", "csharp multi region cluster" } }; // We can only set the witness region for the first cluster var createClusterRequest1 = new CreateClusterRequest { DeletionProtectionEnabled = true, Tags = tags, MultiRegionProperties = new MultiRegionProperties { WitnessRegion = witnessRegion.SystemName } }; var cluster1 = await client1.CreateClusterAsync(createClusterRequest1); var cluster1Arn = cluster1.Arn; Console.WriteLine($"Initiated creation of {cluster1Arn}"); // For the second cluster we can set witness region and designate cluster1 as a peer var createClusterRequest2 = new CreateClusterRequest { DeletionProtectionEnabled = true, Tags = tags, MultiRegionProperties = new MultiRegionProperties { WitnessRegion = witnessRegion.SystemName, Clusters = new List<string> { cluster1.Arn } } }; var cluster2 = await client2.CreateClusterAsync(createClusterRequest2); var cluster2Arn = cluster2.Arn; Console.WriteLine($"Initiated creation of {cluster2Arn}"); // Now that we know the cluster2 arn we can set it as a peer of cluster1 var updateClusterRequest = new UpdateClusterRequest { Identifier = cluster1.Identifier, MultiRegionProperties = new MultiRegionProperties { WitnessRegion = witnessRegion.SystemName, Clusters = new List<string> { cluster2.Arn } } }; await client1.UpdateClusterAsync(updateClusterRequest); Console.WriteLine($"Added {cluster2Arn} as a peer of {cluster1Arn}"); return (cluster1, cluster2); } } private static async Task Main() { var region1 = RegionEndpoint.USEast1; var region2 = RegionEndpoint.USEast2; var witnessRegion = RegionEndpoint.USWest2; var (cluster1, cluster2) = await Create(region1, region2, witnessRegion); Console.WriteLine("Created multi region clusters:"); Console.WriteLine($"Cluster 1: {cluster1.Arn}"); Console.WriteLine($"Cluster 2: {cluster2.Arn}"); } } }
Golang

Use the following example to create a cluster in a single AWS Region.

package main import ( "context" "fmt" "log" "time" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/dsql" ) func CreateCluster(ctx context.Context, region string) error { cfg, err := config.LoadDefaultConfig(ctx, config.WithRegion(region)) if err != nil { log.Fatalf("Failed to load AWS configuration: %v", err) } // Create a DSQL client client := dsql.NewFromConfig(cfg) deleteProtect := true input := dsql.CreateClusterInput{ DeletionProtectionEnabled: &deleteProtect, Tags: map[string]string{ "Name": "go single region cluster", }, } clusterProperties, err := client.CreateCluster(context.Background(), &input) if err != nil { return fmt.Errorf("error creating cluster: %w", err) } fmt.Printf("Created cluster: %s\n", *clusterProperties.Arn) // Create the waiter with our custom options waiter := dsql.NewClusterActiveWaiter(client, func(o *dsql.ClusterActiveWaiterOptions) { o.MaxDelay = 30 * time.Second o.MinDelay = 10 * time.Second o.LogWaitAttempts = true }) id := clusterProperties.Identifier // Create the input for the clusterProperties getInput := &dsql.GetClusterInput{ Identifier: id, } // Wait for the cluster to become active fmt.Println("Waiting for cluster to become ACTIVE") err = waiter.Wait(ctx, getInput, 5*time.Minute) if err != nil { return fmt.Errorf("error waiting for cluster to become active: %w", err) } fmt.Printf("Cluster %s is now active\n", *id) return nil } // Example usage in main function func main() { region := "us-east-1" // Set up context with timeout ctx, cancel := context.WithTimeout(context.Background(), 6*time.Minute) defer cancel() if err := CreateCluster(ctx, region); err != nil { log.Fatalf("Failed to create cluster: %v", err) } }

To create a multi-Region cluster, use the following example. Creating a multi-Region cluster might take some time.

package main import ( "context" "fmt" "log" "time" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/dsql" dtypes "github.com/aws/aws-sdk-go-v2/service/dsql/types" ) func CreateMultiRegionClusters(ctx context.Context, witness, region1, region2 string) error { cfg, err := config.LoadDefaultConfig(ctx, config.WithRegion(region1)) if err != nil { log.Fatalf("Failed to load AWS configuration: %v", err) } // Create a DSQL region 1 client client := dsql.NewFromConfig(cfg) cfg2, err := config.LoadDefaultConfig(ctx, config.WithRegion(region2)) if err != nil { log.Fatalf("Failed to load AWS configuration: %v", err) } // Create a DSQL region 2 client client2 := dsql.NewFromConfig(cfg2, func(o *dsql.Options) { o.Region = region2 }) // Create cluster deleteProtect := true // We can only set the witness region for the first cluster input := &dsql.CreateClusterInput{ DeletionProtectionEnabled: &deleteProtect, MultiRegionProperties: &dtypes.MultiRegionProperties{ WitnessRegion: aws.String(witness), }, Tags: map[string]string{ "Name": "go multi-region cluster", }, } clusterProperties, err := client.CreateCluster(context.Background(), input) if err != nil { return fmt.Errorf("failed to create first cluster: %v", err) } // create second cluster cluster2Arns := []string{*clusterProperties.Arn} // For the second cluster we can set witness region and designate the first cluster as a peer input2 := &dsql.CreateClusterInput{ DeletionProtectionEnabled: &deleteProtect, MultiRegionProperties: &dtypes.MultiRegionProperties{ WitnessRegion: aws.String("us-west-2"), Clusters: cluster2Arns, }, Tags: map[string]string{ "Name": "go multi-region cluster", }, } clusterProperties2, err := client2.CreateCluster(context.Background(), input2) if err != nil { return fmt.Errorf("failed to create second cluster: %v", err) } // link initial cluster to second cluster cluster1Arns := []string{*clusterProperties2.Arn} // Now that we know the second cluster arn we can set it as a peer of the first cluster input3 := dsql.UpdateClusterInput{ Identifier: clusterProperties.Identifier, MultiRegionProperties: &dtypes.MultiRegionProperties{ WitnessRegion: aws.String("us-west-2"), Clusters: cluster1Arns, }} _, err = client.UpdateCluster(context.Background(), &input3) if err != nil { return fmt.Errorf("failed to update cluster to associate with first cluster. %v", err) } // Create the waiter with our custom options for first cluster waiter := dsql.NewClusterActiveWaiter(client, func(o *dsql.ClusterActiveWaiterOptions) { o.MaxDelay = 30 * time.Second // Creating a multi-region cluster can take a few minutes o.MinDelay = 10 * time.Second o.LogWaitAttempts = true }) // Now that multiRegionProperties is fully defined for both clusters // they'll begin the transition to ACTIVE // Create the input for the clusterProperties to monitor for first cluster getInput := &dsql.GetClusterInput{ Identifier: clusterProperties.Identifier, } // Wait for the first cluster to become active fmt.Printf("Waiting for first cluster %s to become active...\n", *clusterProperties.Identifier) err = waiter.Wait(ctx, getInput, 5*time.Minute) if err != nil { return fmt.Errorf("error waiting for first cluster to become active: %w", err) } // Create the waiter with our custom options waiter2 := dsql.NewClusterActiveWaiter(client2, func(o *dsql.ClusterActiveWaiterOptions) { o.MaxDelay = 30 * time.Second // Creating a multi-region cluster can take a few minutes o.MinDelay = 10 * time.Second o.LogWaitAttempts = true }) // Create the input for the clusterProperties to monitor for second getInput2 := &dsql.GetClusterInput{ Identifier: clusterProperties2.Identifier, } // Wait for the second cluster to become active fmt.Printf("Waiting for second cluster %s to become active...\n", *clusterProperties2.Identifier) err = waiter2.Wait(ctx, getInput2, 5*time.Minute) if err != nil { return fmt.Errorf("error waiting for second cluster to become active: %w", err) } fmt.Printf("Cluster %s is now active\n", *clusterProperties.Identifier) fmt.Printf("Cluster %s is now active\n", *clusterProperties2.Identifier) return nil } // Example usage in main function func main() { // Set up context with timeout ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute) defer cancel() err := CreateMultiRegionClusters(ctx, "us-west-2", "us-east-1", "us-east-2") if err != nil { fmt.Printf("failed to create multi-region clusters: %v", err) panic(err) } }