Uso de DescribeOrderableDBInstanceOptions con un AWS SDK o la CLI - Amazon Aurora

Uso de DescribeOrderableDBInstanceOptions con un AWS SDK o la CLI

En los siguientes ejemplos de código, se muestra cómo utilizar DescribeOrderableDBInstanceOptions.

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:

.NET
AWS SDK for .NET
nota

Hay más información en GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

/// <summary> /// Get a list of orderable DB instance options for a specific /// engine and engine version. /// </summary> /// <param name="engine">Name of the engine.</param> /// <param name="engineVersion">Version of the engine.</param> /// <returns>List of OrderableDBInstanceOptions.</returns> public async Task<List<OrderableDBInstanceOption>> DescribeOrderableDBInstanceOptionsPagedAsync(string engine, string engineVersion) { // Use a paginator to get a list of DB instance options. var results = new List<OrderableDBInstanceOption>(); var paginateInstanceOptions = _amazonRDS.Paginators.DescribeOrderableDBInstanceOptions( new DescribeOrderableDBInstanceOptionsRequest() { Engine = engine, EngineVersion = engineVersion, }); // Get the entire list using the paginator. await foreach (var instanceOptions in paginateInstanceOptions.OrderableDBInstanceOptions) { results.Add(instanceOptions); } return results; }
C++
SDK para C++
nota

Hay más en GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::RDS::RDSClient client(clientConfig); //! Routine which gets available DB instance classes, displays the list //! to the user, and returns the user selection. /*! \sa chooseDBInstanceClass() \param engineName: The DB engine name. \param engineVersion: The DB engine version. \param dbInstanceClass: String for DB instance class chosen by the user. \param client: 'RDSClient' instance. \return bool: Successful completion. */ bool AwsDoc::Aurora::chooseDBInstanceClass(const Aws::String &engine, const Aws::String &engineVersion, Aws::String &dbInstanceClass, const Aws::RDS::RDSClient &client) { std::vector<Aws::String> instanceClasses; Aws::String marker; // The marker is used for pagination. do { Aws::RDS::Model::DescribeOrderableDBInstanceOptionsRequest request; request.SetEngine(engine); request.SetEngineVersion(engineVersion); if (!marker.empty()) { request.SetMarker(marker); } Aws::RDS::Model::DescribeOrderableDBInstanceOptionsOutcome outcome = client.DescribeOrderableDBInstanceOptions(request); if (outcome.IsSuccess()) { const Aws::Vector<Aws::RDS::Model::OrderableDBInstanceOption> &options = outcome.GetResult().GetOrderableDBInstanceOptions(); for (const Aws::RDS::Model::OrderableDBInstanceOption &option: options) { const Aws::String &instanceClass = option.GetDBInstanceClass(); if (std::find(instanceClasses.begin(), instanceClasses.end(), instanceClass) == instanceClasses.end()) { instanceClasses.push_back(instanceClass); } } marker = outcome.GetResult().GetMarker(); } else { std::cerr << "Error with Aurora::DescribeOrderableDBInstanceOptions. " << outcome.GetError().GetMessage() << std::endl; return false; } } while (!marker.empty()); std::cout << "The available DB instance classes for your database engine are:" << std::endl; for (int i = 0; i < instanceClasses.size(); ++i) { std::cout << " " << i + 1 << ": " << instanceClasses[i] << std::endl; } int choice = askQuestionForIntRange( "Which DB instance class do you want to use? ", 1, static_cast<int>(instanceClasses.size())); dbInstanceClass = instanceClasses[choice - 1]; return true; }
Go
SDK para Go V2
nota

Hay más en GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

type DbClusters struct { AuroraClient *rds.Client } // GetOrderableInstances uses a paginator to get DB instance options that can be used to create DB instances that are // compatible with a set of specifications. func (clusters *DbClusters) GetOrderableInstances(ctx context.Context, engine string, engineVersion string) ( []types.OrderableDBInstanceOption, error) { var output *rds.DescribeOrderableDBInstanceOptionsOutput var instances []types.OrderableDBInstanceOption var err error orderablePaginator := rds.NewDescribeOrderableDBInstanceOptionsPaginator(clusters.AuroraClient, &rds.DescribeOrderableDBInstanceOptionsInput{ Engine: aws.String(engine), EngineVersion: aws.String(engineVersion), }) for orderablePaginator.HasMorePages() { output, err = orderablePaginator.NextPage(ctx) if err != nil { log.Printf("Couldn't get orderable DB instances: %v\n", err) break } else { instances = append(instances, output.OrderableDBInstanceOptions...) } } return instances, err }
Java
SDK para Java 2.x
nota

Hay más en GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

public static void describeDBEngines(RdsClient rdsClient) { try { DescribeDbEngineVersionsRequest engineVersionsRequest = DescribeDbEngineVersionsRequest.builder() .engine("aurora-mysql") .defaultOnly(true) .maxRecords(20) .build(); DescribeDbEngineVersionsResponse response = rdsClient.describeDBEngineVersions(engineVersionsRequest); List<DBEngineVersion> engines = response.dbEngineVersions(); // Get all DBEngineVersion objects. for (DBEngineVersion engineOb : engines) { System.out.println("The name of the DB parameter group family for the database engine is " + engineOb.dbParameterGroupFamily()); System.out.println("The name of the database engine " + engineOb.engine()); System.out.println("The version number of the database engine " + engineOb.engineVersion()); } } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); System.exit(1); } }
PowerShell
Herramientas para PowerShell

Ejemplo 1: este ejemplo enumera las versiones del motor de base de datos que admiten una clase de instancia de base de datos concreta en una Región de AWS.

$params = @{ Engine = 'aurora-postgresql' DBInstanceClass = 'db.r5.large' Region = 'us-east-1' } Get-RDSOrderableDBInstanceOption @params

Ejemplo 2: este ejemplo enumera las clases de instancia de base de datos que se admiten para una versión de motor de base de datos concreta en una Región de AWS.

$params = @{ Engine = 'aurora-postgresql' EngineVersion = '13.6' Region = 'us-east-1' } Get-RDSOrderableDBInstanceOption @params
Python
SDK para Python (Boto3)
nota

Hay más en GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de 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 get_orderable_instances(self, db_engine, db_engine_version): """ Gets DB instance options that can be used to create DB instances that are compatible with a set of specifications. :param db_engine: The database engine that must be supported by the DB instance. :param db_engine_version: The engine version that must be supported by the DB instance. :return: The list of DB instance options that can be used to create a compatible DB instance. """ try: inst_opts = [] paginator = self.rds_client.get_paginator( "describe_orderable_db_instance_options" ) for page in paginator.paginate( Engine=db_engine, EngineVersion=db_engine_version ): inst_opts += page["OrderableDBInstanceOptions"] except ClientError as err: logger.error( "Couldn't get orderable DB instances. Here's why: %s: %s", err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return inst_opts
Rust
SDK para Rust
nota

Hay más información en GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

pub async fn get_instance_classes(&self) -> Result<Vec<String>, ScenarioError> { let describe_orderable_db_instance_options_items = self .rds .describe_orderable_db_instance_options( DB_ENGINE, self.engine_version .as_ref() .expect("engine version for db instance options") .as_str(), ) .await; describe_orderable_db_instance_options_items .map(|options| { options .iter() .filter(|o| o.storage_type() == Some("aurora")) .map(|o| o.db_instance_class().unwrap_or_default().to_string()) .collect::<Vec<String>>() }) .map_err(|err| ScenarioError::new("Could not get available instance classes", &err)) } pub async fn describe_orderable_db_instance_options( &self, engine: &str, engine_version: &str, ) -> Result<Vec<OrderableDbInstanceOption>, SdkError<DescribeOrderableDBInstanceOptionsError>> { self.inner .describe_orderable_db_instance_options() .engine(engine) .engine_version(engine_version) .into_paginator() .items() .send() .try_collect() .await } #[tokio::test] async fn test_scenario_get_instance_classes() { let mut mock_rds = MockRdsImpl::default(); mock_rds .expect_create_db_cluster_parameter_group() .return_once(|_, _, _| { Ok(CreateDbClusterParameterGroupOutput::builder() .db_cluster_parameter_group(DbClusterParameterGroup::builder().build()) .build()) }); mock_rds .expect_describe_orderable_db_instance_options() .with(eq("aurora-mysql"), eq("aurora-mysql8.0")) .return_once(|_, _| { Ok(vec![ OrderableDbInstanceOption::builder() .db_instance_class("t1") .storage_type("aurora") .build(), OrderableDbInstanceOption::builder() .db_instance_class("t1") .storage_type("aurora-iopt1") .build(), OrderableDbInstanceOption::builder() .db_instance_class("t2") .storage_type("aurora") .build(), OrderableDbInstanceOption::builder() .db_instance_class("t3") .storage_type("aurora") .build(), ]) }); let mut scenario = AuroraScenario::new(mock_rds); scenario .set_engine("aurora-mysql", "aurora-mysql8.0") .await .expect("set engine"); let instance_classes = scenario.get_instance_classes().await; assert_eq!( instance_classes, Ok(vec!["t1".into(), "t2".into(), "t3".into()]) ); } #[tokio::test] async fn test_scenario_get_instance_classes_error() { let mut mock_rds = MockRdsImpl::default(); mock_rds .expect_describe_orderable_db_instance_options() .with(eq("aurora-mysql"), eq("aurora-mysql8.0")) .return_once(|_, _| { Err(SdkError::service_error( DescribeOrderableDBInstanceOptionsError::unhandled(Box::new(Error::new( ErrorKind::Other, "describe_orderable_db_instance_options_error", ))), Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()), )) }); let mut scenario = AuroraScenario::new(mock_rds); scenario.engine_family = Some("aurora-mysql".into()); scenario.engine_version = Some("aurora-mysql8.0".into()); let instance_classes = scenario.get_instance_classes().await; assert_matches!( instance_classes, Err(ScenarioError {message, context: _}) if message == "Could not get available instance classes" ); }

Para obtener una lista completa de las guías para desarrolladores del 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.