Use DeleteDBCluster com um AWS SDK ou CLI - AWS SDKExemplos de código

Há mais AWS SDK exemplos disponíveis no GitHub repositório AWS Doc SDK Examples.

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

Use DeleteDBCluster com um AWS SDK ou CLI

Os exemplos de código a seguir mostram como usar o DeleteDBCluster.

Exemplos de ações são trechos de código de programas maiores e devem ser executados em contexto. É possível ver essa ação no contexto no seguinte exemplo de código:

.NET
AWS SDK for .NET
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

/// <summary> /// Delete a particular DB cluster. /// </summary> /// <param name="dbClusterIdentifier">DB cluster identifier.</param> /// <returns>DB cluster object.</returns> public async Task<DBCluster> DeleteDBClusterByIdentifierAsync(string dbClusterIdentifier) { var response = await _amazonRDS.DeleteDBClusterAsync( new DeleteDBClusterRequest() { DBClusterIdentifier = dbClusterIdentifier, SkipFinalSnapshot = true }); return response.DBCluster; }
  • Para API obter detalhes, consulte D eleteDBCluster em AWS SDK for .NET APIReferência.

C++
SDKpara C++
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

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::DeleteDBClusterRequest request; request.SetDBClusterIdentifier(dbClusterIdentifier); request.SetSkipFinalSnapshot(true); Aws::RDS::Model::DeleteDBClusterOutcome outcome = client.DeleteDBCluster(request); if (outcome.IsSuccess()) { std::cout << "DB cluster deletion has started." << std::endl; clusterDeleting = true; std::cout << "Waiting for DB cluster to delete before deleting the parameter group." << std::endl; std::cout << "This may take a while." << std::endl; } else { std::cerr << "Error with Aurora::DeleteDBCluster. " << outcome.GetError().GetMessage() << std::endl; result = false; }
  • Para API obter detalhes, consulte D eleteDBCluster em AWS SDK for C++ APIReferência.

Go
SDKpara Go V2
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

type DbClusters struct { AuroraClient *rds.Client } // DeleteDbCluster deletes a DB cluster without keeping a final snapshot. func (clusters *DbClusters) DeleteDbCluster(clusterName string) error { _, err := clusters.AuroraClient.DeleteDBCluster(context.TODO(), &rds.DeleteDBClusterInput{ DBClusterIdentifier: aws.String(clusterName), SkipFinalSnapshot: aws.Bool(true), }) if err != nil { log.Printf("Couldn't delete DB cluster %v: %v\n", clusterName, err) return err } else { return nil } }
  • Para API obter detalhes, consulte D eleteDBCluster em AWS SDK for Go APIReferência.

Java
SDKpara Java 2.x
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

public static void deleteCluster(RdsClient rdsClient, String dbInstanceClusterIdentifier) { try { DeleteDbClusterRequest deleteDbClusterRequest = DeleteDbClusterRequest.builder() .dbClusterIdentifier(dbInstanceClusterIdentifier) .skipFinalSnapshot(true) .build(); rdsClient.deleteDBCluster(deleteDbClusterRequest); System.out.println(dbInstanceClusterIdentifier + " was deleted!"); } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); System.exit(1); } }
  • Para API obter detalhes, consulte D eleteDBCluster em AWS SDK for Java 2.x APIReferência.

Kotlin
SDKpara Kotlin
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

suspend fun deleteCluster(dbInstanceClusterIdentifier: String) { val deleteDbClusterRequest = DeleteDbClusterRequest { dbClusterIdentifier = dbInstanceClusterIdentifier skipFinalSnapshot = true } RdsClient { region = "us-west-2" }.use { rdsClient -> rdsClient.deleteDbCluster(deleteDbClusterRequest) println("$dbInstanceClusterIdentifier was deleted!") } }
  • Para API obter detalhes, consulte D eleteDBCluster in AWS SDKpara referência ao Kotlin API.

Python
SDKpara Python (Boto3)
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

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 delete_db_cluster(self, cluster_name): """ Deletes a DB cluster. :param cluster_name: The name of the DB cluster to delete. """ try: self.rds_client.delete_db_cluster( DBClusterIdentifier=cluster_name, SkipFinalSnapshot=True ) logger.info("Deleted DB cluster %s.", cluster_name) except ClientError: logger.exception("Couldn't delete DB cluster %s.", cluster_name) raise
  • Para API obter detalhes, consulte D eleteDBCluster in AWS SDKfor Python (Boto3) Reference. API

Rust
SDKpara Rust
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

pub async fn clean_up(self) -> Result<(), Vec<ScenarioError>> { let mut clean_up_errors: Vec<ScenarioError> = vec![]; // Delete the instance. rds.DeleteDbInstance. let delete_db_instance = self .rds .delete_db_instance( self.db_instance_identifier .as_deref() .expect("instance identifier"), ) .await; if let Err(err) = delete_db_instance { let identifier = self .db_instance_identifier .as_deref() .unwrap_or("Missing Instance Identifier"); let message = format!("failed to delete db instance {identifier}"); clean_up_errors.push(ScenarioError::new(message, &err)); } else { // Wait for the instance to delete let waiter = Waiter::default(); while waiter.sleep().await.is_ok() { let describe_db_instances = self.rds.describe_db_instances().await; if let Err(err) = describe_db_instances { clean_up_errors.push(ScenarioError::new( "Failed to check instance state during deletion", &err, )); break; } let db_instances = describe_db_instances .unwrap() .db_instances() .iter() .filter(|instance| instance.db_cluster_identifier == self.db_cluster_identifier) .cloned() .collect::<Vec<DbInstance>>(); if db_instances.is_empty() { trace!("Delete Instance waited and no instances were found"); break; } match db_instances.first().unwrap().db_instance_status() { Some("Deleting") => continue, Some(status) => { info!("Attempting to delete but instances is in {status}"); continue; } None => { warn!("No status for DB instance"); break; } } } } // Delete the DB cluster. rds.DeleteDbCluster. let delete_db_cluster = self .rds .delete_db_cluster( self.db_cluster_identifier .as_deref() .expect("cluster identifier"), ) .await; if let Err(err) = delete_db_cluster { let identifier = self .db_cluster_identifier .as_deref() .unwrap_or("Missing DB Cluster Identifier"); let message = format!("failed to delete db cluster {identifier}"); clean_up_errors.push(ScenarioError::new(message, &err)); } else { // Wait for the instance and cluster to fully delete. rds.DescribeDbInstances and rds.DescribeDbClusters until both are not found. let waiter = Waiter::default(); while waiter.sleep().await.is_ok() { let describe_db_clusters = self .rds .describe_db_clusters( self.db_cluster_identifier .as_deref() .expect("cluster identifier"), ) .await; if let Err(err) = describe_db_clusters { clean_up_errors.push(ScenarioError::new( "Failed to check cluster state during deletion", &err, )); break; } let describe_db_clusters = describe_db_clusters.unwrap(); let db_clusters = describe_db_clusters.db_clusters(); if db_clusters.is_empty() { trace!("Delete cluster waited and no clusters were found"); break; } match db_clusters.first().unwrap().status() { Some("Deleting") => continue, Some(status) => { info!("Attempting to delete but clusters is in {status}"); continue; } None => { warn!("No status for DB cluster"); break; } } } } // Delete the DB cluster parameter group. rds.DeleteDbClusterParameterGroup. let delete_db_cluster_parameter_group = self .rds .delete_db_cluster_parameter_group( self.db_cluster_parameter_group .map(|g| { g.db_cluster_parameter_group_name .unwrap_or_else(|| DB_CLUSTER_PARAMETER_GROUP_NAME.to_string()) }) .as_deref() .expect("cluster parameter group name"), ) .await; if let Err(error) = delete_db_cluster_parameter_group { clean_up_errors.push(ScenarioError::new( "Failed to delete the db cluster parameter group", &error, )) } if clean_up_errors.is_empty() { Ok(()) } else { Err(clean_up_errors) } } pub async fn delete_db_cluster( &self, cluster_identifier: &str, ) -> Result<DeleteDbClusterOutput, SdkError<DeleteDBClusterError>> { self.inner .delete_db_cluster() .db_cluster_identifier(cluster_identifier) .skip_final_snapshot(true) .send() .await } #[tokio::test] async fn test_scenario_clean_up() { let mut mock_rds = MockRdsImpl::default(); mock_rds .expect_delete_db_instance() .with(eq("MockInstance")) .return_once(|_| Ok(DeleteDbInstanceOutput::builder().build())); mock_rds .expect_describe_db_instances() .with() .times(1) .returning(|| { Ok(DescribeDbInstancesOutput::builder() .db_instances( DbInstance::builder() .db_cluster_identifier("MockCluster") .db_instance_status("Deleting") .build(), ) .build()) }) .with() .times(1) .returning(|| Ok(DescribeDbInstancesOutput::builder().build())); mock_rds .expect_delete_db_cluster() .with(eq("MockCluster")) .return_once(|_| Ok(DeleteDbClusterOutput::builder().build())); mock_rds .expect_describe_db_clusters() .with(eq("MockCluster")) .times(1) .returning(|id| { Ok(DescribeDbClustersOutput::builder() .db_clusters( DbCluster::builder() .db_cluster_identifier(id) .status("Deleting") .build(), ) .build()) }) .with(eq("MockCluster")) .times(1) .returning(|_| Ok(DescribeDbClustersOutput::builder().build())); mock_rds .expect_delete_db_cluster_parameter_group() .with(eq("MockParamGroup")) .return_once(|_| Ok(DeleteDbClusterParameterGroupOutput::builder().build())); let mut scenario = AuroraScenario::new(mock_rds); scenario.db_cluster_identifier = Some(String::from("MockCluster")); scenario.db_instance_identifier = Some(String::from("MockInstance")); scenario.db_cluster_parameter_group = Some( DbClusterParameterGroup::builder() .db_cluster_parameter_group_name("MockParamGroup") .build(), ); tokio::time::pause(); let assertions = tokio::spawn(async move { let clean_up = scenario.clean_up().await; assert!(clean_up.is_ok()); }); tokio::time::advance(Duration::from_secs(1)).await; // Wait for first Describe Instances tokio::time::advance(Duration::from_secs(1)).await; // Wait for second Describe Instances tokio::time::advance(Duration::from_secs(1)).await; // Wait for first Describe Cluster tokio::time::advance(Duration::from_secs(1)).await; // Wait for second Describe Cluster tokio::time::resume(); let _ = assertions.await; } #[tokio::test] async fn test_scenario_clean_up_errors() { let mut mock_rds = MockRdsImpl::default(); mock_rds .expect_delete_db_instance() .with(eq("MockInstance")) .return_once(|_| Ok(DeleteDbInstanceOutput::builder().build())); mock_rds .expect_describe_db_instances() .with() .times(1) .returning(|| { Ok(DescribeDbInstancesOutput::builder() .db_instances( DbInstance::builder() .db_cluster_identifier("MockCluster") .db_instance_status("Deleting") .build(), ) .build()) }) .with() .times(1) .returning(|| { Err(SdkError::service_error( DescribeDBInstancesError::unhandled(Box::new(Error::new( ErrorKind::Other, "describe db instances error", ))), Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()), )) }); mock_rds .expect_delete_db_cluster() .with(eq("MockCluster")) .return_once(|_| Ok(DeleteDbClusterOutput::builder().build())); mock_rds .expect_describe_db_clusters() .with(eq("MockCluster")) .times(1) .returning(|id| { Ok(DescribeDbClustersOutput::builder() .db_clusters( DbCluster::builder() .db_cluster_identifier(id) .status("Deleting") .build(), ) .build()) }) .with(eq("MockCluster")) .times(1) .returning(|_| { Err(SdkError::service_error( DescribeDBClustersError::unhandled(Box::new(Error::new( ErrorKind::Other, "describe db clusters error", ))), Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()), )) }); mock_rds .expect_delete_db_cluster_parameter_group() .with(eq("MockParamGroup")) .return_once(|_| Ok(DeleteDbClusterParameterGroupOutput::builder().build())); let mut scenario = AuroraScenario::new(mock_rds); scenario.db_cluster_identifier = Some(String::from("MockCluster")); scenario.db_instance_identifier = Some(String::from("MockInstance")); scenario.db_cluster_parameter_group = Some( DbClusterParameterGroup::builder() .db_cluster_parameter_group_name("MockParamGroup") .build(), ); tokio::time::pause(); let assertions = tokio::spawn(async move { let clean_up = scenario.clean_up().await; assert!(clean_up.is_err()); let errs = clean_up.unwrap_err(); assert_eq!(errs.len(), 2); assert_matches!(errs.get(0), Some(ScenarioError {message, context: _}) if message == "Failed to check instance state during deletion"); assert_matches!(errs.get(1), Some(ScenarioError {message, context: _}) if message == "Failed to check cluster state during deletion"); }); tokio::time::advance(Duration::from_secs(1)).await; // Wait for first Describe Instances tokio::time::advance(Duration::from_secs(1)).await; // Wait for second Describe Instances tokio::time::advance(Duration::from_secs(1)).await; // Wait for first Describe Cluster tokio::time::advance(Duration::from_secs(1)).await; // Wait for second Describe Cluster tokio::time::resume(); let _ = assertions.await; }
  • Para API obter detalhes, consulte D eleteDBCluster in AWS SDKpara API referência ao Rust.