与 AWS SDK或CreateCluster一起使用 CLI - AWS SDK代码示例

AWS 文档 AWS SDK示例 GitHub 存储库中还有更多SDK示例

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

与 AWS SDK或CreateCluster一起使用 CLI

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

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

CLI
AWS CLI

使用最小值创建集群 ParametersThis 示例使用最少的参数集创建集群。默认情况下,输出采用 JSON format.Command:

aws redshift create-cluster --node-type dw.hs1.xlarge --number-of-nodes 2 --master-username adminuser --master-user-password TopSecret1 --cluster-identifier mycluster

结果:

{ "Cluster": { "NodeType": "dw.hs1.xlarge", "ClusterVersion": "1.0", "PubliclyAccessible": "true", "MasterUsername": "adminuser", "ClusterParameterGroups": [ { "ParameterApplyStatus": "in-sync", "ParameterGroupName": "default.redshift-1.0" } ], "ClusterSecurityGroups": [ { "Status": "active", "ClusterSecurityGroupName": "default" } ], "AllowVersionUpgrade": true, "VpcSecurityGroups": \[], "PreferredMaintenanceWindow": "sat:03:30-sat:04:00", "AutomatedSnapshotRetentionPeriod": 1, "ClusterStatus": "creating", "ClusterIdentifier": "mycluster", "DBName": "dev", "NumberOfNodes": 2, "PendingModifiedValues": { "MasterUserPassword": "\****" } }, "ResponseMetadata": { "RequestId": "7cf4bcfc-64dd-11e2-bea9-49e0ce183f07" } }
Go
SDK适用于 Go V2
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

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 } // CreateCluster sends a request to create a cluster with the given clusterId using the provided credentials. func (actor RedshiftActions) CreateCluster(ctx context.Context, clusterId string, userName string, userPassword string, nodeType string, clusterType string, publiclyAccessible bool) (*redshift.CreateClusterOutput, error) { // Create a new Redshift cluster input := &redshift.CreateClusterInput{ ClusterIdentifier: aws.String(clusterId), MasterUserPassword: aws.String(userPassword), MasterUsername: aws.String(userName), NodeType: aws.String(nodeType), ClusterType: aws.String(clusterType), PubliclyAccessible: aws.Bool(publiclyAccessible), } var opErr *types.ClusterAlreadyExistsFault output, err := actor.RedshiftClient.CreateCluster(ctx, input) if err != nil && errors.As(err, &opErr) { log.Println("Cluster already exists") return nil, nil } else if err != nil { log.Printf("Failed to create Redshift cluster: %v\n", err) return nil, err } log.Printf("Created cluster %s\n", *output.Cluster.ClusterIdentifier) return output, nil }
  • 有关API详细信息,请参阅 “AWS SDK for Go API参考 CreateCluster” 中的。

Java
SDK适用于 Java 2.x
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

创建集群。

/** * Creates a new Amazon Redshift cluster asynchronously. * @param clusterId the unique identifier for the cluster * @param username the username for the administrative user * @param userPassword the password for the administrative user * @return a CompletableFuture that represents the asynchronous operation of creating the cluster * @throws RuntimeException if the cluster creation fails */ public CompletableFuture<CreateClusterResponse> createClusterAsync(String clusterId, String username, String userPassword) { CreateClusterRequest clusterRequest = CreateClusterRequest.builder() .clusterIdentifier(clusterId) .masterUsername(username) .masterUserPassword(userPassword) .nodeType("ra3.4xlarge") .publiclyAccessible(true) .numberOfNodes(2) .build(); return getAsyncClient().createCluster(clusterRequest) .whenComplete((response, exception) -> { if (response != null) { logger.info("Created cluster "); } else { throw new RuntimeException("Failed to create cluster: " + exception.getMessage(), exception); } }); }
  • 有关API详细信息,请参阅 “AWS SDK for Java 2.x API参考 CreateCluster” 中的。

JavaScript
SDK对于 JavaScript (v3)
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

创建客户端。

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 };

创建集群。

// Import required AWS SDK clients and commands for Node.js import { CreateClusterCommand } from "@aws-sdk/client-redshift"; import { redshiftClient } from "./libs/redshiftClient.js"; const params = { ClusterIdentifier: "CLUSTER_NAME", // Required NodeType: "NODE_TYPE", //Required MasterUsername: "MASTER_USER_NAME", // Required - must be lowercase MasterUserPassword: "MASTER_USER_PASSWORD", // Required - must contain at least one uppercase letter, and one number ClusterType: "CLUSTER_TYPE", // Required IAMRoleARN: "IAM_ROLE_ARN", // Optional - the ARN of an IAM role with permissions your cluster needs to access other AWS services on your behalf, such as Amazon S3. ClusterSubnetGroupName: "CLUSTER_SUBNET_GROUPNAME", //Optional - the name of a cluster subnet group to be associated with this cluster. Defaults to 'default' if not specified. DBName: "DATABASE_NAME", // Optional - defaults to 'dev' if not specified Port: "PORT_NUMBER", // Optional - defaults to '5439' if not specified }; const run = async () => { try { const data = await redshiftClient.send(new CreateClusterCommand(params)); console.log( `Cluster ${data.Cluster.ClusterIdentifier} successfully created`, ); return data; // For unit tests. } catch (err) { console.log("Error", err); } }; run();
  • 有关API详细信息,请参阅 “AWS SDK for JavaScript API参考 CreateCluster” 中的。

Kotlin
SDK对于 Kotlin 来说
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

创建集群。

suspend fun createCluster( clusterId: String?, masterUsernameVal: String?, masterUserPasswordVal: String?, ) { val clusterRequest = CreateClusterRequest { clusterIdentifier = clusterId masterUsername = masterUsernameVal masterUserPassword = masterUserPasswordVal nodeType = "ra3.4xlarge" publiclyAccessible = true numberOfNodes = 2 } RedshiftClient { region = "us-east-1" }.use { redshiftClient -> val clusterResponse = redshiftClient.createCluster(clusterRequest) println("Created cluster ${clusterResponse.cluster?.clusterIdentifier}") } }
  • 有关API详细信息,请参阅CreateCluster中的 Kotlin AWS SDK API 参考

Python
SDK适用于 Python (Boto3)
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

class RedshiftWrapper: """ Encapsulates Amazon Redshift cluster operations. """ def __init__(self, redshift_client): """ :param redshift_client: A Boto3 Redshift client. """ self.client = redshift_client def create_cluster( self, cluster_identifier, node_type, master_username, master_user_password, publicly_accessible, number_of_nodes, ): """ Creates a cluster. :param cluster_identifier: The name of the cluster. :param node_type: The type of node in the cluster. :param master_username: The master username. :param master_user_password: The master user password. :param publicly_accessible: Whether the cluster is publicly accessible. :param number_of_nodes: The number of nodes in the cluster. :return: The cluster. """ try: cluster = self.client.create_cluster( ClusterIdentifier=cluster_identifier, NodeType=node_type, MasterUsername=master_username, MasterUserPassword=master_user_password, PubliclyAccessible=publicly_accessible, NumberOfNodes=number_of_nodes, ) return cluster except ClientError as err: logging.error( "Couldn't create a cluster. Here's why: %s: %s", err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise

以下代码实例化对象。 RedshiftWrapper

client = boto3.client("redshift") redhift_wrapper = RedshiftWrapper(client)
  • 有关API详细信息,请参阅CreateCluster中的 AWS SDKPython (Boto3) API 参考。