Amazon RDS examples using SDK for Ruby - Amazon SDK for Ruby
Services or capabilities described in Amazon Web Services documentation might vary by Region. To see the differences applicable to the China Regions, see Getting Started with Amazon Web Services in China (PDF).

Amazon RDS examples using SDK for Ruby

The following code examples show you how to perform actions and implement common scenarios by using the Amazon SDK for Ruby with Amazon RDS.

Actions are code excerpts from larger programs and must be run in context. While actions show you how to call individual service functions, you can see actions in context in their related scenarios and cross-service examples.

Scenarios are code examples that show you how to accomplish a specific task by calling multiple functions within the same service.

Each example includes a link to GitHub, where you can find instructions on how to set up and run the code in context.

Get started

The following code examples show how to get started using Amazon RDS.

SDK for Ruby
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

require 'aws-sdk-rds' require 'logger' # RDSManager is a class responsible for managing RDS operations # such as listing all RDS DB instances in the current AWS account. class RDSManager def initialize(client) @client = client @logger = Logger.new($stdout) end # Lists and prints all RDS DB instances in the current AWS account. def list_db_instances @logger.info('Listing RDS DB instances') paginator = @client.describe_db_instances instances = [] paginator.each_page do |page| instances.concat(page.db_instances) end if instances.empty? @logger.info('No instances found.') else @logger.info("Found #{instances.count} instance(s):") instances.each do |instance| @logger.info(" * #{instance.db_instance_identifier} (#{instance.db_instance_status})") end end end end if $PROGRAM_NAME == __FILE__ rds_client = Aws::RDS::Client.new(region: 'us-west-2') manager = RDSManager.new(rds_client) manager.list_db_instances end

Actions

The following code example shows how to use CreateDBSnapshot.

SDK for Ruby
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

require "aws-sdk-rds" # v2: require 'aws-sdk' # Create a snapshot for an Amazon Relational Database Service (Amazon RDS) # DB instance. # # @param rds_resource [Aws::RDS::Resource] The resource containing SDK logic. # @param db_instance_name [String] The name of the Amazon RDS DB instance. # @return [Aws::RDS::DBSnapshot, nil] The snapshot created, or nil if error. def create_snapshot(rds_resource, db_instance_name) id = "snapshot-#{rand(10**6)}" db_instance = rds_resource.db_instance(db_instance_name) db_instance.create_snapshot({ db_snapshot_identifier: id }) rescue Aws::Errors::ServiceError => e puts "Couldn't create DB instance snapshot #{id}:\n #{e.message}" end

The following code example shows how to use DescribeDBInstances.

SDK for Ruby
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

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

The following code example shows how to use DescribeDBParameterGroups.

SDK for Ruby
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

require "aws-sdk-rds" # v2: require 'aws-sdk' # List all Amazon Relational Database Service (Amazon RDS) parameter groups. # # @param rds_resource [Aws::RDS::Resource] An SDK for Ruby Amazon RDS resource. # @return [Array, nil] List of all parameter groups, or nil if error. def list_parameter_groups(rds_resource) parameter_groups = [] rds_resource.db_parameter_groups.each do |p| parameter_groups.append({ "name": p.db_parameter_group_name, "description": p.description }) end parameter_groups rescue Aws::Errors::ServiceError => e puts "Couldn't list parameter groups:\n #{e.message}" end

The following code example shows how to use DescribeDBParameters.

SDK for Ruby
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

require "aws-sdk-rds" # v2: require 'aws-sdk' # List all Amazon Relational Database Service (Amazon RDS) parameter groups. # # @param rds_resource [Aws::RDS::Resource] An SDK for Ruby Amazon RDS resource. # @return [Array, nil] List of all parameter groups, or nil if error. def list_parameter_groups(rds_resource) parameter_groups = [] rds_resource.db_parameter_groups.each do |p| parameter_groups.append({ "name": p.db_parameter_group_name, "description": p.description }) end parameter_groups rescue Aws::Errors::ServiceError => e puts "Couldn't list parameter groups:\n #{e.message}" end

The following code example shows how to use DescribeDBSnapshots.

SDK for Ruby
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

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

Serverless examples

The following code example shows how to implement a Lambda function that connects to an RDS database. The function makes a simple database request and returns the result.

SDK for Ruby
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository.

Connecting to an Amazon RDS database in a Lambda function using Ruby.

# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 # Ruby code here. require 'aws-sdk-rds' require 'json' require 'mysql2' def lambda_handler(event:, context:) endpoint = ENV['DBEndpoint'] # Add the endpoint without https" port = ENV['Port'] # 3306 user = ENV['DBUser'] region = ENV['DBRegion'] # 'us-east-1' db_name = ENV['DBName'] credentials = Aws::Credentials.new( ENV['AWS_ACCESS_KEY_ID'], ENV['AWS_SECRET_ACCESS_KEY'], ENV['AWS_SESSION_TOKEN'] ) rds_client = Aws::RDS::AuthTokenGenerator.new( region: region, credentials: credentials ) token = rds_client.auth_token( endpoint: endpoint+ ':' + port, user_name: user, region: region ) begin conn = Mysql2::Client.new( host: endpoint, username: user, password: token, port: port, database: db_name, sslca: '/var/task/global-bundle.pem', sslverify: true, enable_cleartext_plugin: true ) a = 3 b = 2 result = conn.query("SELECT #{a} + #{b} AS sum").first['sum'] puts result conn.close { statusCode: 200, body: result.to_json } rescue => e puts "Database connection failed due to #{e}" end end