Usar DeleteCluster com o AWS SDK ou a CLI - Amazon Redshift

O Amazon Redshift não permitirá mais a criação de funções definidas pelo usuário (UDFs) do Python a partir de 1.º de novembro de 2025. Se quiser usar UDFs do Python, você deve criá-las antes dessa data. As UDFs do Python existentes continuarão a funcionar normalmente. Para ter mais informações, consulte a publicação de blog .

Usar DeleteCluster com o AWS SDK ou a CLI

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

.NET
SDK for .NET (v4)
nota

Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWSCode Examples Repository.

/// <summary> /// Delete an Amazon Redshift cluster without a final snapshot. /// </summary> /// <param name="clusterIdentifier">The identifier for the cluster.</param> /// <returns>True if successful.</returns> public async Task<bool> DeleteClusterWithoutSnapshotAsync(string clusterIdentifier) { try { var request = new DeleteClusterRequest { ClusterIdentifier = clusterIdentifier, SkipFinalClusterSnapshot = true }; var response = await _redshiftClient.DeleteClusterAsync(request); Console.WriteLine($"The {clusterIdentifier} was deleted"); return true; } catch (ClusterNotFoundException ex) { Console.WriteLine($"Cluster not found: {ex.Message}"); return false; } catch (Exception ex) { Console.WriteLine($"Couldn't delete cluster. Here's why: {ex.Message}"); return false; } }
  • Consulte detalhes da API em DeleteCluster na Referência da API AWS SDK for .NET.

CLI
AWS CLI

Excluir um cluster sem um snapshot final do cluster Este exemplo exclui um cluster, forçando a exclusão de dados, para que nenhum snapshot final do cluster seja criado. Comando:

aws redshift delete-cluster --cluster-identifier mycluster --skip-final-cluster-snapshot

Excluir um cluster, permitindo a criação de um snapshot final do cluster Este exemplo exclui um cluster, mas especifica o snapshot final do cluster. Comando:

aws redshift delete-cluster --cluster-identifier mycluster --final-cluster-snapshot-identifier myfinalsnapshot
  • Para ver detalhes da API, consulte DeleteCluster em AWS CLI Command Reference.

Go
SDK para Go V2
nota

Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWSCode Examples Repository.

import ( "context" "errors" "log" "time" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/redshift" "github.com/aws/aws-sdk-go-v2/service/redshift/types" ) // RedshiftActions wraps Redshift service actions. type RedshiftActions struct { RedshiftClient *redshift.Client } // DeleteCluster deletes the given cluster. func (actor RedshiftActions) DeleteCluster(ctx context.Context, clusterId string) (bool, error) { input := redshift.DeleteClusterInput{ ClusterIdentifier: aws.String(clusterId), SkipFinalClusterSnapshot: aws.Bool(true), } _, err := actor.RedshiftClient.DeleteCluster(ctx, &input) var opErr *types.ClusterNotFoundFault if err != nil && errors.As(err, &opErr) { log.Println("Cluster was not found. Where could it be?") return false, err } else if err != nil { log.Printf("Failed to delete Redshift cluster: %v\n", err) return false, err } waiter := redshift.NewClusterDeletedWaiter(actor.RedshiftClient) err = waiter.Wait(ctx, &redshift.DescribeClustersInput{ ClusterIdentifier: aws.String(clusterId), }, 5*time.Minute) if err != nil { log.Printf("Wait time exceeded for deleting cluster, continuing: %v\n", err) } log.Printf("The cluster %s was deleted\n", clusterId) return true, nil }
  • Consulte detalhes da API em DeleteCluster na Referência da API AWS SDK para Go.

Java
SDK para Java 2.x
nota

Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWSCode Examples Repository.

Excluir o cluster.

/** * Deletes a Redshift cluster asynchronously. * * @param clusterId the identifier of the Redshift cluster to be deleted * @return a {@link CompletableFuture} that represents the asynchronous operation of deleting the Redshift cluster */ public CompletableFuture<DeleteClusterResponse> deleteRedshiftClusterAsync(String clusterId) { DeleteClusterRequest deleteClusterRequest = DeleteClusterRequest.builder() .clusterIdentifier(clusterId) .skipFinalClusterSnapshot(true) .build(); return getAsyncClient().deleteCluster(deleteClusterRequest) .whenComplete((response, exception) -> { if (exception != null) { // Handle exceptions if (exception.getCause() instanceof RedshiftException) { logger.info("Error: {}", exception.getMessage()); } else { logger.info("Unexpected error: {}", exception.getMessage()); } } else { // Handle successful response logger.info("The status is {}", response.cluster().clusterStatus()); } }); }
  • Consulte detalhes da API em DeleteCluster na Referência da API AWS SDK for Java 2.x.

JavaScript
SDK para JavaScript (v3)
nota

Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWSCode Examples Repository.

Crie o cliente.

import { RedshiftClient } from "@aws-sdk/client-redshift"; // Set the AWS Region. const REGION = "REGION"; //Set the Redshift Service Object const redshiftClient = new RedshiftClient({ region: REGION }); export { redshiftClient };

Crie o cluster.

// Import required AWS SDK clients and commands for Node.js import { DeleteClusterCommand } from "@aws-sdk/client-redshift"; import { redshiftClient } from "./libs/redshiftClient.js"; const params = { ClusterIdentifier: "CLUSTER_NAME", SkipFinalClusterSnapshot: false, FinalClusterSnapshotIdentifier: "CLUSTER_SNAPSHOT_ID", }; const run = async () => { try { const data = await redshiftClient.send(new DeleteClusterCommand(params)); console.log("Success, cluster deleted. ", data); return data; // For unit tests. } catch (err) { console.log("Error", err); } }; run();
  • Consulte detalhes da API em DeleteCluster na Referência da API AWS SDK for JavaScript.

Kotlin
SDK para Kotlin
nota

Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWSCode Examples Repository.

Excluir o cluster.

suspend fun deleteRedshiftCluster(clusterId: String?) { val request = DeleteClusterRequest { clusterIdentifier = clusterId skipFinalClusterSnapshot = true } RedshiftClient.fromEnvironment { region = "us-west-2" }.use { redshiftClient -> val response = redshiftClient.deleteCluster(request) println("The status is ${response.cluster?.clusterStatus}") } }
  • Para ver detalhes da API, consulte ExcluirCluster em AWS SDK for Kotlin API Reference.

Python
SDK para Python (Boto3).
nota

Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWSCode Examples Repository.

class RedshiftWrapper: """ Encapsulates Amazon Redshift cluster operations. """ def __init__(self, redshift_client): """ :param redshift_client: A Boto3 Redshift client. """ self.client = redshift_client def delete_cluster(self, cluster_identifier): """ Deletes a cluster. :param cluster_identifier: The cluster identifier. """ try: self.client.delete_cluster( ClusterIdentifier=cluster_identifier, SkipFinalClusterSnapshot=True ) except ClientError as err: logging.error( "Couldn't delete a cluster. Here's why: %s: %s", err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise

O código a seguir instancia o objeto RedshiftWrapper.

client = boto3.client("redshift") redhift_wrapper = RedshiftWrapper(client)
  • Para ver detalhes da API, consulte DeleteCluster em AWS SDK for Python (Boto3) API Reference.

Para ver uma lista completa dos guias de desenvolvedor e exemplos de código do SDK da AWS, consulte Usar este serviço com um AWS SDK. Este tópico também inclui informações sobre como começar e detalhes sobre versões anteriores do SDK.