Usar DescribeClusters 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 DescribeClusters com o AWS SDK ou a CLI

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

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 em contexto no seguinte exemplo de código:

.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> /// Describe Amazon Redshift clusters. /// </summary> /// <param name="clusterIdentifier">Optional cluster identifier to describe a specific cluster.</param> /// <returns>A list of clusters.</returns> public async Task<List<Cluster>> DescribeClustersAsync(string? clusterIdentifier = null) { try { var clusters = new List<Cluster>(); var request = new DescribeClustersRequest(); if (!string.IsNullOrEmpty(clusterIdentifier)) { request.ClusterIdentifier = clusterIdentifier; } var clustersPaginator = _redshiftClient.Paginators.DescribeClusters(request); await foreach (var response in clustersPaginator.Responses) { if (response.Clusters != null) clusters.AddRange(response.Clusters); } Console.WriteLine($"{clusters.Count} cluster(s) retrieved."); foreach (var cluster in clusters) { Console.WriteLine($"\t{cluster.ClusterIdentifier} (Status: {cluster.ClusterStatus})"); } return clusters; } catch (ClusterNotFoundException ex) { Console.WriteLine($"Cluster {clusterIdentifier} not found: {ex.Message}"); throw; } catch (Exception ex) { Console.WriteLine($"Couldn't describe clusters. Here's why: {ex.Message}"); throw; } }
  • Consulte detalhes da API em DescribeClusters na Referência da API AWS SDK for .NET.

CLI
AWS CLI

Obter uma descrição de todos os clusters Este exemplo retorna uma descrição de todos os clusters da conta. Por padrão, o formato da saída é JSON. Comando:

aws redshift describe-clusters

Resultado:

{ "Clusters": [ { "NodeType": "dw.hs1.xlarge", "Endpoint": { "Port": 5439, "Address": "mycluster.coqoarplqhsn.us-east-1.redshift.amazonaws.com" }, "ClusterVersion": "1.0", "PubliclyAccessible": "true", "MasterUsername": "adminuser", "ClusterParameterGroups": [ { "ParameterApplyStatus": "in-sync", "ParameterGroupName": "default.redshift-1.0" } ], "ClusterSecurityGroups": [ { "Status": "active", "ClusterSecurityGroupName": "default" } ], "AllowVersionUpgrade": true, "VpcSecurityGroups": \[], "AvailabilityZone": "us-east-1a", "ClusterCreateTime": "2013-01-22T21:59:29.559Z", "PreferredMaintenanceWindow": "sat:03:30-sat:04:00", "AutomatedSnapshotRetentionPeriod": 1, "ClusterStatus": "available", "ClusterIdentifier": "mycluster", "DBName": "dev", "NumberOfNodes": 2, "PendingModifiedValues": {} } ], "ResponseMetadata": { "RequestId": "65b71cac-64df-11e2-8f5b-e90bd6c77476" } }

Você pode obter as mesmas informações em formato de texto com a opção --output text. Comando:

opção --output text. Comando:

opção. Comando:

aws redshift describe-clusters --output text

Resultado:

dw.hs1.xlarge 1.0 true adminuser True us-east-1a 2013-01-22T21:59:29.559Z sat:03:30-sat:04:00 1 available mycluster dev 2 ENDPOINT 5439 mycluster.coqoarplqhsn.us-east-1.redshift.amazonaws.com in-sync default.redshift-1.0 active default PENDINGMODIFIEDVALUES RESPONSEMETADATA 934281a8-64df-11e2-b07c-f7fbdd006c67
  • Para ver detalhes da API, consulte DescribeClusters 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 } // DescribeClusters returns information about the given cluster. func (actor RedshiftActions) DescribeClusters(ctx context.Context, clusterId string) (*redshift.DescribeClustersOutput, error) { input, err := actor.RedshiftClient.DescribeClusters(ctx, &redshift.DescribeClustersInput{ ClusterIdentifier: aws.String(clusterId), }) var opErr *types.AccessToClusterDeniedFault if errors.As(err, &opErr) { println("Access to cluster denied.") panic(err) } else if err != nil { println("Failed to describe Redshift clusters.") return nil, err } return input, nil }
  • Consulte detalhes da API em DescribeClusters 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.

Descrever o cluster.

/** * Waits asynchronously for the specified cluster to become available. * @param clusterId the identifier of the cluster to wait for * @return a {@link CompletableFuture} that completes when the cluster is ready */ public CompletableFuture<Void> waitForClusterReadyAsync(String clusterId) { DescribeClustersRequest clustersRequest = DescribeClustersRequest.builder() .clusterIdentifier(clusterId) .build(); logger.info("Waiting for cluster to become available. This may take a few minutes."); long startTime = System.currentTimeMillis(); // Recursive method to poll the cluster status. return checkClusterStatusAsync(clustersRequest, startTime); } private CompletableFuture<Void> checkClusterStatusAsync(DescribeClustersRequest clustersRequest, long startTime) { return getAsyncClient().describeClusters(clustersRequest) .thenCompose(clusterResponse -> { List<Cluster> clusterList = clusterResponse.clusters(); boolean clusterReady = false; for (Cluster cluster : clusterList) { if ("available".equals(cluster.clusterStatus())) { clusterReady = true; break; } } if (clusterReady) { logger.info(String.format("Cluster is available!")); return CompletableFuture.completedFuture(null); } else { long elapsedTimeMillis = System.currentTimeMillis() - startTime; long elapsedSeconds = elapsedTimeMillis / 1000; long minutes = elapsedSeconds / 60; long seconds = elapsedSeconds % 60; System.out.printf("\rElapsed Time: %02d:%02d - Waiting for cluster...", minutes, seconds); System.out.flush(); // Wait 1 second before the next status check return CompletableFuture.runAsync(() -> { try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { throw new RuntimeException("Error during sleep: " + e.getMessage(), e); } }).thenCompose(ignored -> checkClusterStatusAsync(clustersRequest, startTime)); } }).exceptionally(exception -> { throw new RuntimeException("Failed to get cluster status: " + exception.getMessage(), exception); }); }
  • Consulte detalhes da API em DescribeClusters 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 };

Descreva os clusters.

// Import required AWS SDK clients and commands for Node.js import { DescribeClustersCommand } from "@aws-sdk/client-redshift"; import { redshiftClient } from "./libs/redshiftClient.js"; const params = { ClusterIdentifier: "CLUSTER_NAME", }; const run = async () => { try { const data = await redshiftClient.send(new DescribeClustersCommand(params)); console.log("Success", data); return data; // For unit tests. } catch (err) { console.log("Error", err); } }; run();
  • Consulte detalhes da API em DescribeClusters 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.

Descrever o cluster.

suspend fun describeRedshiftClusters() { RedshiftClient.fromEnvironment { region = "us-west-2" }.use { redshiftClient -> val clusterResponse = redshiftClient.describeClusters(DescribeClustersRequest {}) val clusterList = clusterResponse.clusters if (clusterList != null) { for (cluster in clusterList) { println("Cluster database name is ${cluster.dbName}") println("Cluster status is ${cluster.clusterStatus}") } } } }
  • Para ver detalhes da API, consulte DescreverClusters 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 describe_clusters(self, cluster_identifier): """ Describes a cluster. :param cluster_identifier: The cluster identifier. :return: A list of clusters. """ try: kwargs = {} if cluster_identifier: kwargs["ClusterIdentifier"] = cluster_identifier paginator = self.client.get_paginator("describe_clusters") clusters = [] for page in paginator.paginate(**kwargs): clusters.extend(page["Clusters"]) return clusters except ClientError as err: logging.error( "Couldn't describe 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 DescribeClusters 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.