Uso de CreateCluster
con un AWS SDK o la CLI
En los siguientes ejemplos de código, se muestra cómo utilizar CreateCluster
.
Los ejemplos de acciones son extractos de código de programas más grandes y deben ejecutarse en contexto. Puede ver esta acción en contexto en el siguiente ejemplo de código:
- CLI
-
- AWS CLI
-
Crear un clúster con parámetros mínimos En este ejemplo, se crea un clúster con el conjunto mínimo de parámetros. De forma predeterminada, la salida es en 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
Resultado:
{
"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 para Go V2
-
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"
)
type RedshiftActions struct {
RedshiftClient *redshift.Client
}
func (actor RedshiftActions) CreateCluster(ctx context.Context, clusterId string, userName string, userPassword string, nodeType string, clusterType string, publiclyAccessible bool) (*redshift.CreateClusterOutput, error) {
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
}
- Java
-
- SDK para Java 2.x
-
Cree el clúster.
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);
}
});
}
- JavaScript
-
- SDK para JavaScript (v3)
-
Cree el cliente.
import { RedshiftClient } from "@aws-sdk/client-redshift";
const REGION = "REGION";
const redshiftClient = new RedshiftClient({ region: REGION });
export { redshiftClient };
Cree el clúster.
import { CreateClusterCommand } from "@aws-sdk/client-redshift";
import { redshiftClient } from "./libs/redshiftClient.js";
const params = {
ClusterIdentifier: "CLUSTER_NAME",
NodeType: "NODE_TYPE",
MasterUsername: "MASTER_USER_NAME",
MasterUserPassword: "MASTER_USER_PASSWORD",
ClusterType: "CLUSTER_TYPE",
IAMRoleARN: "IAM_ROLE_ARN",
ClusterSubnetGroupName: "CLUSTER_SUBNET_GROUPNAME",
DBName: "DATABASE_NAME",
Port: "PORT_NUMBER",
};
const run = async () => {
try {
const data = await redshiftClient.send(new CreateClusterCommand(params));
console.log(
`Cluster ${data.Cluster.ClusterIdentifier} successfully created`,
);
return data;
} catch (err) {
console.log("Error", err);
}
};
run();
- Kotlin
-
- SDK para Kotlin
-
Cree el clúster.
suspend fun createCluster(
clusterId: String?,
masterUsernameVal: String?,
masterUserPasswordVal: String?,
) {
val clusterRequest =
CreateClusterRequest {
clusterIdentifier = clusterId
availabilityZone = "us-east-1a"
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}")
}
}
- Python
-
- SDK para Python (Boto3)
-
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
El código siguiente crea una instancia del objeto RedshiftWrapper.
client = boto3.client("redshift")
redhift_wrapper = RedshiftWrapper(client)
Para obtener una lista completa de las guías para desarrolladores de AWS SDK y ejemplos de código, consulte Uso de este servicio con un SDK de AWS. En este tema también se incluye información sobre cómo comenzar a utilizar el SDK y detalles sobre sus versiones anteriores.