Use DescribeDBInstances com um AWS SDK ou CLI - AWS SDKExemplos de código

Há mais AWS SDK exemplos disponíveis no GitHub repositório AWS Doc SDK Examples.

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

Use DescribeDBInstances com um AWS SDK ou CLI

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

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

.NET
AWS SDK for .NET
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

/// <summary> /// Returns a list of DB instances. /// </summary> /// <param name="dbInstanceIdentifier">Optional name of a specific DB instance.</param> /// <returns>List of DB instances.</returns> public async Task<List<DBInstance>> DescribeDBInstances(string dbInstanceIdentifier = null) { var results = new List<DBInstance>(); var instancesPaginator = _amazonRDS.Paginators.DescribeDBInstances( new DescribeDBInstancesRequest { DBInstanceIdentifier = dbInstanceIdentifier }); // Get the entire list using the paginator. await foreach (var instances in instancesPaginator.DBInstances) { results.Add(instances); } return results; }
C++
SDKpara C++
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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 a DB instance description. /*! \sa describeDBInstance() \param dbInstanceIdentifier: A DB instance identifier. \param instanceResult: The 'DBInstance' object containing the description. \param client: 'RDSClient' instance. \return bool: Successful completion. */ bool AwsDoc::RDS::describeDBInstance(const Aws::String &dbInstanceIdentifier, Aws::RDS::Model::DBInstance &instanceResult, const Aws::RDS::RDSClient &client) { Aws::RDS::Model::DescribeDBInstancesRequest request; request.SetDBInstanceIdentifier(dbInstanceIdentifier); Aws::RDS::Model::DescribeDBInstancesOutcome outcome = client.DescribeDBInstances(request); bool result = true; if (outcome.IsSuccess()) { instanceResult = outcome.GetResult().GetDBInstances()[0]; } else if (outcome.GetError().GetErrorType() != Aws::RDS::RDSErrors::D_B_INSTANCE_NOT_FOUND_FAULT) { result = false; std::cerr << "Error with RDS::DescribeDBInstances. " << outcome.GetError().GetMessage() << std::endl; } // This example does not log an error if the DB instance does not exist. // Instead, instanceResult is set to empty. else { instanceResult = Aws::RDS::Model::DBInstance(); } return result; }
CLI
AWS CLI

Como descrever uma instância de banco de dados

O exemplo de describe-db-instances a seguir recupera detalhes sobre a instância de banco de dados especificada.

aws rds describe-db-instances \ --db-instance-identifier mydbinstancecf

Saída:

{ "DBInstances": [ { "DBInstanceIdentifier": "mydbinstancecf", "DBInstanceClass": "db.t3.small", "Engine": "mysql", "DBInstanceStatus": "available", "MasterUsername": "masterawsuser", "Endpoint": { "Address": "mydbinstancecf.abcexample.us-east-1.rds.amazonaws.com", "Port": 3306, "HostedZoneId": "Z2R2ITUGPM61AM" }, ...some output truncated... } ] }
Go
SDKpara Go V2
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

import ( "context" "errors" "log" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/rds" "github.com/aws/aws-sdk-go-v2/service/rds/types" ) type DbInstances struct { RdsClient *rds.Client } // GetInstance gets data about a DB instance. func (instances *DbInstances) GetInstance(ctx context.Context, instanceName string) ( *types.DBInstance, error) { output, err := instances.RdsClient.DescribeDBInstances(ctx, &rds.DescribeDBInstancesInput{ DBInstanceIdentifier: aws.String(instanceName), }) if err != nil { var notFoundError *types.DBInstanceNotFoundFault if errors.As(err, &notFoundError) { log.Printf("DB instance %v does not exist.\n", instanceName) err = nil } else { log.Printf("Couldn't get instance %v: %v\n", instanceName, err) } return nil, err } else { return &output.DBInstances[0], nil } }
Java
SDKpara Java 2.x
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.rds.RdsClient; import software.amazon.awssdk.services.rds.model.DescribeDbInstancesResponse; import software.amazon.awssdk.services.rds.model.DBInstance; import software.amazon.awssdk.services.rds.model.RdsException; import java.util.List; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class DescribeDBInstances { public static void main(String[] args) { Region region = Region.US_EAST_1; RdsClient rdsClient = RdsClient.builder() .region(region) .build(); describeInstances(rdsClient); rdsClient.close(); } public static void describeInstances(RdsClient rdsClient) { try { DescribeDbInstancesResponse response = rdsClient.describeDBInstances(); List<DBInstance> instanceList = response.dbInstances(); for (DBInstance instance : instanceList) { System.out.println("Instance ARN is: " + instance.dbInstanceArn()); System.out.println("The Engine is " + instance.engine()); System.out.println("Connection endpoint is" + instance.endpoint().address()); } } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); System.exit(1); } } }
Kotlin
SDKpara Kotlin
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

suspend fun describeInstances() { RdsClient { region = "us-west-2" }.use { rdsClient -> val response = rdsClient.describeDbInstances(DescribeDbInstancesRequest {}) response.dbInstances?.forEach { instance -> println("Instance Identifier is ${instance.dbInstanceIdentifier}") println("The Engine is ${instance.engine}") println("Connection endpoint is ${instance.endpoint?.address}") } } }
PHP
SDK para PHP
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

require __DIR__ . '/vendor/autoload.php'; use Aws\Exception\AwsException; //Create an RDSClient $rdsClient = new Aws\Rds\RdsClient([ 'region' => 'us-east-2' ]); try { $result = $rdsClient->describeDBInstances(); foreach ($result['DBInstances'] as $instance) { print('<p>DB Identifier: ' . $instance['DBInstanceIdentifier']); print('<br />Endpoint: ' . $instance['Endpoint']["Address"] . ':' . $instance['Endpoint']["Port"]); print('<br />Current Status: ' . $instance["DBInstanceStatus"]); print('</p>'); } print(" Raw Result "); var_dump($result); } catch (AwsException $e) { echo $e->getMessage(); echo "\n"; }
Python
SDKpara Python (Boto3)
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

class InstanceWrapper: """Encapsulates Amazon RDS DB instance actions.""" def __init__(self, rds_client): """ :param rds_client: A Boto3 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_db_instance(self, instance_id): """ Gets data about a DB instance. :param instance_id: The ID of the DB instance to retrieve. :return: The retrieved DB instance. """ try: response = self.rds_client.describe_db_instances( DBInstanceIdentifier=instance_id ) db_inst = response["DBInstances"][0] except ClientError as err: if err.response["Error"]["Code"] == "DBInstanceNotFound": logger.info("Instance %s does not exist.", instance_id) else: logger.error( "Couldn't get DB instance %s. Here's why: %s: %s", instance_id, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return db_inst
  • Para API obter detalhes, consulte D escribeDBInstances in AWS SDKfor Python (Boto3) Reference. API

Ruby
SDKpara Ruby
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

require 'aws-sdk-rds' # v2: require 'aws-sdk' # List all Amazon Relational Database Service (Amazon RDS) DB instances. # # @param rds_resource [Aws::RDS::Resource] An SDK for Ruby Amazon RDS resource. # @return [Array, nil] List of all DB instances, or nil if error. def list_instances(rds_resource) db_instances = [] rds_resource.db_instances.each do |i| db_instances.append({ "name": i.id, "status": i.db_instance_status }) end db_instances rescue Aws::Errors::ServiceError => e puts "Couldn't list instances:\n#{e.message}" end