将 CreateDBCluster 与 Amazon SDK 或 CLI 配合使用 - Amazon Aurora
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

CreateDBCluster 与 Amazon SDK 或 CLI 配合使用

以下代码示例演示如何使用 CreateDBCluster

操作示例是大型程序的代码摘录,必须在上下文中运行。在以下代码示例中,您可以查看此操作的上下文:

.NET
Amazon SDK for .NET
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

/// <summary> /// Create a new cluster and database. /// </summary> /// <param name="dbName">The name of the new database.</param> /// <param name="clusterIdentifier">The identifier of the cluster.</param> /// <param name="parameterGroupName">The name of the parameter group.</param> /// <param name="dbEngine">The engine to use for the new cluster.</param> /// <param name="dbEngineVersion">The version of the engine to use.</param> /// <param name="adminName">The admin username.</param> /// <param name="adminPassword">The primary admin password.</param> /// <returns>The cluster object.</returns> public async Task<DBCluster> CreateDBClusterWithAdminAsync( string dbName, string clusterIdentifier, string parameterGroupName, string dbEngine, string dbEngineVersion, string adminName, string adminPassword) { var request = new CreateDBClusterRequest { DatabaseName = dbName, DBClusterIdentifier = clusterIdentifier, DBClusterParameterGroupName = parameterGroupName, Engine = dbEngine, EngineVersion = dbEngineVersion, MasterUsername = adminName, MasterUserPassword = adminPassword, }; var response = await _amazonRDS.CreateDBClusterAsync(request); return response.DBCluster; }
  • 有关 API 详细信息,请参阅《Amazon SDK for .NET API 参考》中的 CreateDBCluster

C++
适用于 C++ 的 SDK
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::RDS::RDSClient client(clientConfig); Aws::RDS::Model::CreateDBClusterRequest request; request.SetDBClusterIdentifier(DB_CLUSTER_IDENTIFIER); request.SetDBClusterParameterGroupName(CLUSTER_PARAMETER_GROUP_NAME); request.SetEngine(engineName); request.SetEngineVersion(engineVersionName); request.SetMasterUsername(administratorName); request.SetMasterUserPassword(administratorPassword); Aws::RDS::Model::CreateDBClusterOutcome outcome = client.CreateDBCluster(request); if (outcome.IsSuccess()) { std::cout << "The DB cluster creation has started." << std::endl; } else { std::cerr << "Error with Aurora::CreateDBCluster. " << outcome.GetError().GetMessage() << std::endl; cleanUpResources(CLUSTER_PARAMETER_GROUP_NAME, "", "", client); return false; }
  • 有关 API 详细信息,请参阅《Amazon SDK for C++ API 参考》中的 CreateDBCluster

Go
适用于 Go V2 的 SDK
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

type DbClusters struct { AuroraClient *rds.Client } // CreateDbCluster creates a DB cluster that is configured to use the specified parameter group. // The newly created DB cluster contains a database that uses the specified engine and // engine version. func (clusters *DbClusters) CreateDbCluster(clusterName string, parameterGroupName string, dbName string, dbEngine string, dbEngineVersion string, adminName string, adminPassword string) ( *types.DBCluster, error) { output, err := clusters.AuroraClient.CreateDBCluster(context.TODO(), &rds.CreateDBClusterInput{ DBClusterIdentifier: aws.String(clusterName), Engine: aws.String(dbEngine), DBClusterParameterGroupName: aws.String(parameterGroupName), DatabaseName: aws.String(dbName), EngineVersion: aws.String(dbEngineVersion), MasterUserPassword: aws.String(adminPassword), MasterUsername: aws.String(adminName), }) if err != nil { log.Printf("Couldn't create DB cluster %v: %v\n", clusterName, err) return nil, err } else { return output.DBCluster, err } }
  • 有关 API 详细信息,请参阅《Amazon SDK for Go API 参考》中的 CreateDBCluster

Java
SDK for Java 2.x
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

public static String createDBCluster(RdsClient rdsClient, String dbParameterGroupFamily, String dbName, String dbClusterIdentifier, String userName, String password) { try { CreateDbClusterRequest clusterRequest = CreateDbClusterRequest.builder() .databaseName(dbName) .dbClusterIdentifier(dbClusterIdentifier) .dbClusterParameterGroupName(dbParameterGroupFamily) .engine("aurora-mysql") .masterUsername(userName) .masterUserPassword(password) .build(); CreateDbClusterResponse response = rdsClient.createDBCluster(clusterRequest); return response.dbCluster().dbClusterArn(); } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); System.exit(1); } return ""; }
  • 有关 API 详细信息,请参阅《Amazon SDK for Java 2.x API 参考》中的 CreateDBCluster

Kotlin
适用于 Kotlin 的 SDK
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

suspend fun createDBCluster( dbParameterGroupFamilyVal: String?, dbName: String?, dbClusterIdentifierVal: String?, userName: String?, password: String?, ): String? { val clusterRequest = CreateDbClusterRequest { databaseName = dbName dbClusterIdentifier = dbClusterIdentifierVal dbClusterParameterGroupName = dbParameterGroupFamilyVal engine = "aurora-mysql" masterUsername = userName masterUserPassword = password } RdsClient { region = "us-west-2" }.use { rdsClient -> val response = rdsClient.createDbCluster(clusterRequest) return response.dbCluster?.dbClusterArn } }
  • 有关 API 详细信息,请参阅《Amazon SDK for Kotlin API 参考》中的 CreateDBCluster

Python
SDK for Python(Boto3)
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

class AuroraWrapper: """Encapsulates Aurora DB cluster actions.""" def __init__(self, rds_client): """ :param rds_client: A Boto3 Amazon Relational Database Service (Amazon RDS) client. """ self.rds_client = rds_client @classmethod def from_client(cls): """ Instantiates this class from a Boto3 client. """ rds_client = boto3.client("rds") return cls(rds_client) def create_db_cluster( self, cluster_name, parameter_group_name, db_name, db_engine, db_engine_version, admin_name, admin_password, ): """ Creates a DB cluster that is configured to use the specified parameter group. The newly created DB cluster contains a database that uses the specified engine and engine version. :param cluster_name: The name of the DB cluster to create. :param parameter_group_name: The name of the parameter group to associate with the DB cluster. :param db_name: The name of the database to create. :param db_engine: The database engine of the database that is created, such as MySql. :param db_engine_version: The version of the database engine. :param admin_name: The user name of the database administrator. :param admin_password: The password of the database administrator. :return: The newly created DB cluster. """ try: response = self.rds_client.create_db_cluster( DatabaseName=db_name, DBClusterIdentifier=cluster_name, DBClusterParameterGroupName=parameter_group_name, Engine=db_engine, EngineVersion=db_engine_version, MasterUsername=admin_name, MasterUserPassword=admin_password, ) cluster = response["DBCluster"] except ClientError as err: logger.error( "Couldn't create database %s. Here's why: %s: %s", db_name, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return cluster
  • 有关 API 详细信息,请参阅《Amazon SDK for Python (Boto3) API 参考》中的 CreateDBCluster

Rust
适用于 Rust 的 SDK
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

// Get a list of allowed engine versions. rds.DescribeDbEngineVersions(Engine='aurora-mysql', DBParameterGroupFamily=<the family used to create your parameter group in step 2>) // Create an Aurora DB cluster database cluster that contains a MySql database and uses the parameter group you created. // Wait for DB cluster to be ready. Call rds.DescribeDBClusters and check for Status == 'available'. // Get a list of instance classes available for the selected engine and engine version. rds.DescribeOrderableDbInstanceOptions(Engine='mysql', EngineVersion=). // Create a database instance in the cluster. // Wait for DB instance to be ready. Call rds.DescribeDbInstances and check for DBInstanceStatus == 'available'. pub async fn start_cluster_and_instance(&mut self) -> Result<(), ScenarioError> { if self.password.is_none() { return Err(ScenarioError::with( "Must set Secret Password before starting a cluster", )); } let create_db_cluster = self .rds .create_db_cluster( DB_CLUSTER_IDENTIFIER, DB_CLUSTER_PARAMETER_GROUP_NAME, DB_ENGINE, self.engine_version.as_deref().expect("engine version"), self.username.as_deref().expect("username"), self.password .replace(SecretString::new("".to_string())) .expect("password"), ) .await; if let Err(err) = create_db_cluster { return Err(ScenarioError::new( "Failed to create DB Cluster with cluster group", &err, )); } self.db_cluster_identifier = create_db_cluster .unwrap() .db_cluster .and_then(|c| c.db_cluster_identifier); if self.db_cluster_identifier.is_none() { return Err(ScenarioError::with("Created DB Cluster missing Identifier")); } info!( "Started a db cluster: {}", self.db_cluster_identifier .as_deref() .unwrap_or("Missing ARN") ); let create_db_instance = self .rds .create_db_instance( self.db_cluster_identifier.as_deref().expect("cluster name"), DB_INSTANCE_IDENTIFIER, self.instance_class.as_deref().expect("instance class"), DB_ENGINE, ) .await; if let Err(err) = create_db_instance { return Err(ScenarioError::new( "Failed to create Instance in DB Cluster", &err, )); } self.db_instance_identifier = create_db_instance .unwrap() .db_instance .and_then(|i| i.db_instance_identifier); // Cluster creation can take up to 20 minutes to become available let cluster_max_wait = Duration::from_secs(20 * 60); let waiter = Waiter::builder().max(cluster_max_wait).build(); while waiter.sleep().await.is_ok() { let cluster = self .rds .describe_db_clusters( self.db_cluster_identifier .as_deref() .expect("cluster identifier"), ) .await; if let Err(err) = cluster { warn!(?err, "Failed to describe cluster while waiting for ready"); continue; } let instance = self .rds .describe_db_instance( self.db_instance_identifier .as_deref() .expect("instance identifier"), ) .await; if let Err(err) = instance { return Err(ScenarioError::new( "Failed to find instance for cluster", &err, )); } let instances_available = instance .unwrap() .db_instances() .iter() .all(|instance| instance.db_instance_status() == Some("Available")); let endpoints = self .rds .describe_db_cluster_endpoints( self.db_cluster_identifier .as_deref() .expect("cluster identifier"), ) .await; if let Err(err) = endpoints { return Err(ScenarioError::new( "Failed to find endpoint for cluster", &err, )); } let endpoints_available = endpoints .unwrap() .db_cluster_endpoints() .iter() .all(|endpoint| endpoint.status() == Some("available")); if instances_available && endpoints_available { return Ok(()); } } Err(ScenarioError::with("timed out waiting for cluster")) } pub async fn create_db_cluster( &self, name: &str, parameter_group: &str, engine: &str, version: &str, username: &str, password: SecretString, ) -> Result<CreateDbClusterOutput, SdkError<CreateDBClusterError>> { self.inner .create_db_cluster() .db_cluster_identifier(name) .db_cluster_parameter_group_name(parameter_group) .engine(engine) .engine_version(version) .master_username(username) .master_user_password(password.expose_secret()) .send() .await } #[tokio::test] async fn test_start_cluster_and_instance() { let mut mock_rds = MockRdsImpl::default(); mock_rds .expect_create_db_cluster() .withf(|id, params, engine, version, username, password| { assert_eq!(id, "RustSDKCodeExamplesDBCluster"); assert_eq!(params, "RustSDKCodeExamplesDBParameterGroup"); assert_eq!(engine, "aurora-mysql"); assert_eq!(version, "aurora-mysql8.0"); assert_eq!(username, "test username"); assert_eq!(password.expose_secret(), "test password"); true }) .return_once(|id, _, _, _, _, _| { Ok(CreateDbClusterOutput::builder() .db_cluster(DbCluster::builder().db_cluster_identifier(id).build()) .build()) }); mock_rds .expect_create_db_instance() .withf(|cluster, name, class, engine| { assert_eq!(cluster, "RustSDKCodeExamplesDBCluster"); assert_eq!(name, "RustSDKCodeExamplesDBInstance"); assert_eq!(class, "m5.large"); assert_eq!(engine, "aurora-mysql"); true }) .return_once(|cluster, name, class, _| { Ok(CreateDbInstanceOutput::builder() .db_instance( DbInstance::builder() .db_cluster_identifier(cluster) .db_instance_identifier(name) .db_instance_class(class) .build(), ) .build()) }); mock_rds .expect_describe_db_clusters() .with(eq("RustSDKCodeExamplesDBCluster")) .return_once(|id| { Ok(DescribeDbClustersOutput::builder() .db_clusters(DbCluster::builder().db_cluster_identifier(id).build()) .build()) }); mock_rds .expect_describe_db_instance() .with(eq("RustSDKCodeExamplesDBInstance")) .return_once(|name| { Ok(DescribeDbInstancesOutput::builder() .db_instances( DbInstance::builder() .db_instance_identifier(name) .db_instance_status("Available") .build(), ) .build()) }); mock_rds .expect_describe_db_cluster_endpoints() .with(eq("RustSDKCodeExamplesDBCluster")) .return_once(|_| { Ok(DescribeDbClusterEndpointsOutput::builder() .db_cluster_endpoints(DbClusterEndpoint::builder().status("available").build()) .build()) }); let mut scenario = AuroraScenario::new(mock_rds); scenario.engine_version = Some("aurora-mysql8.0".into()); scenario.instance_class = Some("m5.large".into()); scenario.username = Some("test username".into()); scenario.password = Some(SecretString::new("test password".into())); tokio::time::pause(); let assertions = tokio::spawn(async move { let create = scenario.start_cluster_and_instance().await; assert!(create.is_ok()); assert!(scenario .password .replace(SecretString::new("BAD SECRET".into())) .unwrap() .expose_secret() .is_empty()); assert_eq!( scenario.db_cluster_identifier, Some("RustSDKCodeExamplesDBCluster".into()) ); }); tokio::time::advance(Duration::from_secs(1)).await; tokio::time::resume(); let _ = assertions.await; } #[tokio::test] async fn test_start_cluster_and_instance_cluster_create_error() { let mut mock_rds = MockRdsImpl::default(); mock_rds .expect_create_db_cluster() .return_once(|_, _, _, _, _, _| { Err(SdkError::service_error( CreateDBClusterError::unhandled(Box::new(Error::new( ErrorKind::Other, "create db cluster error", ))), Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()), )) }); let mut scenario = AuroraScenario::new(mock_rds); scenario.engine_version = Some("aurora-mysql8.0".into()); scenario.instance_class = Some("m5.large".into()); scenario.username = Some("test username".into()); scenario.password = Some(SecretString::new("test password".into())); let create = scenario.start_cluster_and_instance().await; assert_matches!(create, Err(ScenarioError { message, context: _}) if message == "Failed to create DB Cluster with cluster group") } #[tokio::test] async fn test_start_cluster_and_instance_cluster_create_missing_id() { let mut mock_rds = MockRdsImpl::default(); mock_rds .expect_create_db_cluster() .return_once(|_, _, _, _, _, _| { Ok(CreateDbClusterOutput::builder() .db_cluster(DbCluster::builder().build()) .build()) }); let mut scenario = AuroraScenario::new(mock_rds); scenario.engine_version = Some("aurora-mysql8.0".into()); scenario.instance_class = Some("m5.large".into()); scenario.username = Some("test username".into()); scenario.password = Some(SecretString::new("test password".into())); let create = scenario.start_cluster_and_instance().await; assert_matches!(create, Err(ScenarioError { message, context:_ }) if message == "Created DB Cluster missing Identifier"); } #[tokio::test] async fn test_start_cluster_and_instance_instance_create_error() { let mut mock_rds = MockRdsImpl::default(); mock_rds .expect_create_db_cluster() .withf(|id, params, engine, version, username, password| { assert_eq!(id, "RustSDKCodeExamplesDBCluster"); assert_eq!(params, "RustSDKCodeExamplesDBParameterGroup"); assert_eq!(engine, "aurora-mysql"); assert_eq!(version, "aurora-mysql8.0"); assert_eq!(username, "test username"); assert_eq!(password.expose_secret(), "test password"); true }) .return_once(|id, _, _, _, _, _| { Ok(CreateDbClusterOutput::builder() .db_cluster(DbCluster::builder().db_cluster_identifier(id).build()) .build()) }); mock_rds .expect_create_db_instance() .return_once(|_, _, _, _| { Err(SdkError::service_error( CreateDBInstanceError::unhandled(Box::new(Error::new( ErrorKind::Other, "create db instance error", ))), Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()), )) }); let mut scenario = AuroraScenario::new(mock_rds); scenario.engine_version = Some("aurora-mysql8.0".into()); scenario.instance_class = Some("m5.large".into()); scenario.username = Some("test username".into()); scenario.password = Some(SecretString::new("test password".into())); let create = scenario.start_cluster_and_instance().await; assert_matches!(create, Err(ScenarioError { message, context: _ }) if message == "Failed to create Instance in DB Cluster") } #[tokio::test] async fn test_start_cluster_and_instance_wait_hiccup() { let mut mock_rds = MockRdsImpl::default(); mock_rds .expect_create_db_cluster() .withf(|id, params, engine, version, username, password| { assert_eq!(id, "RustSDKCodeExamplesDBCluster"); assert_eq!(params, "RustSDKCodeExamplesDBParameterGroup"); assert_eq!(engine, "aurora-mysql"); assert_eq!(version, "aurora-mysql8.0"); assert_eq!(username, "test username"); assert_eq!(password.expose_secret(), "test password"); true }) .return_once(|id, _, _, _, _, _| { Ok(CreateDbClusterOutput::builder() .db_cluster(DbCluster::builder().db_cluster_identifier(id).build()) .build()) }); mock_rds .expect_create_db_instance() .withf(|cluster, name, class, engine| { assert_eq!(cluster, "RustSDKCodeExamplesDBCluster"); assert_eq!(name, "RustSDKCodeExamplesDBInstance"); assert_eq!(class, "m5.large"); assert_eq!(engine, "aurora-mysql"); true }) .return_once(|cluster, name, class, _| { Ok(CreateDbInstanceOutput::builder() .db_instance( DbInstance::builder() .db_cluster_identifier(cluster) .db_instance_identifier(name) .db_instance_class(class) .build(), ) .build()) }); mock_rds .expect_describe_db_clusters() .with(eq("RustSDKCodeExamplesDBCluster")) .times(1) .returning(|_| { Err(SdkError::service_error( DescribeDBClustersError::unhandled(Box::new(Error::new( ErrorKind::Other, "describe cluster error", ))), Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()), )) }) .with(eq("RustSDKCodeExamplesDBCluster")) .times(1) .returning(|id| { Ok(DescribeDbClustersOutput::builder() .db_clusters(DbCluster::builder().db_cluster_identifier(id).build()) .build()) }); mock_rds.expect_describe_db_instance().return_once(|name| { Ok(DescribeDbInstancesOutput::builder() .db_instances( DbInstance::builder() .db_instance_identifier(name) .db_instance_status("Available") .build(), ) .build()) }); mock_rds .expect_describe_db_cluster_endpoints() .return_once(|_| { Ok(DescribeDbClusterEndpointsOutput::builder() .db_cluster_endpoints(DbClusterEndpoint::builder().status("available").build()) .build()) }); let mut scenario = AuroraScenario::new(mock_rds); scenario.engine_version = Some("aurora-mysql8.0".into()); scenario.instance_class = Some("m5.large".into()); scenario.username = Some("test username".into()); scenario.password = Some(SecretString::new("test password".into())); tokio::time::pause(); let assertions = tokio::spawn(async move { let create = scenario.start_cluster_and_instance().await; assert!(create.is_ok()); }); tokio::time::advance(Duration::from_secs(1)).await; tokio::time::advance(Duration::from_secs(1)).await; tokio::time::resume(); let _ = assertions.await; }
  • 有关 API 详细信息,请参阅《Amazon SDK for Rust API 参考》中的 CreateDBCluster

有关 Amazon SDK 开发人员指南和代码示例的完整列表,请参阅 将此服务与 Amazon SDK 结合使用。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。