2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

MySQL 互換 Aurora Serverless の Data API を AWS SDK for Ruby で実行してみる

Posted at

はじめに

Amazon Aurora Serverless の Data API が MySQL 互換のバージョンで使えるようになっていますね。

どんな形で使えるのか、AWS SDK for Ruby で実行して試してみました。

前提

以下は準備できていることとします。

  • Amazon Aurora: MySQL 互換 のインスタンス
  • Aurora のキャパシティタイプ: Serverless
  • Web Service Data API: 有効化
  • AWS SDK for Ruby V3 が使えるようになっている

※ Amazon Aurora は無料では利用できないようですので、料金など確認の上検証してください。

tl;dr

以下のような形でできました。

sample.rb
require 'aws-sdk'

# 認証情報設定
Aws.config.update({
  credentials: Aws::Credentials.new('AWS_ACCESS_KEY', 'AWS_SECRET_ACCESS_KEY')
})

# Data API から SQL 実行
client = Aws::RDSDataService::Client.new(region: 'ap-northeast-1')
resp = client.execute_statement({
  secret_arn: "arn:aws:secretsmanager:ap-northeast-1:000000000000:secret:rds-db-credentials/xxxx", # Aurora クラスター作成時の暗号化キーの ARN(Secrets Manager で確認可能)
  resource_arn: "arn:aws:rds:ap-northeast-1:000000000000:cluster:xxx", # Aurora クラスターの ARN
  sql: "select TABLE_SCHEMA, TABLE_NAME from information_schema.tables LIMIT 3;", # 検証用 SQL
})

# レスポンスを表示
resp.records.each do |record|
  puts "#{record[0].string_value} #{record[1].string_value}"
end

上記を実行すると、以下のようなレスポンスが返却されます。

$ ruby sample.rb

information_schema CHARACTER_SETS
information_schema COLLATIONS
information_schema COLLATION_CHARACTER_SET_APPLICABILITY

レスポンスについて

レスポンスは Aws::RDSDataService::Types::ExecuteStatementResponse クラスのオブジェクトで返却されます。

そのオブジェクトの中の records メソッドで Array<Array<Types::Field>>という形の2次元配列が取得できます。

1つ1つのデータは、Aws::RDSDataService::Types::Field クラスのオブジェクトで表されています。今回は string_value メソッドから値を取得できました。

ハマったエラー

Aws::Errors::MissingCredentialsError: unable to sign request without credentials set

実行するときはアクセスキーを指定しましょう。
参考 issue: https://github.com/aws/aws-sdk-ruby/issues/1951

Aws.config.update({
  credentials: Aws::Credentials.new('ACCESS_KEY', 'SECRET_ACCESS_KEY')
})

Aws::RDSDataService::Errors::BadRequestException: This API is deprecated and not available. Use ExecuteStatement API instead

execute_sql メソッドは deprecated のようです。

おわりに

AWS SDK for Ruby で Aurora Serverless の Data API を実行することができました。
便利に使うにはここからデータの加工が必要かもしれませんが、最低限確認出来てよかったです。

参考

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?