Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configuring a Lambda function(Ruby) to access Amazon RDS(mysql) and do CRUD operations

I need to configure lambda function to access RDS db(mysql) using Ruby code. I found one blog which is doing same but it's in python. Can anyone help me how we can do it using Ruby code?

like image 967
Jeet Avatar asked Aug 13 '26 18:08

Jeet


1 Answers

Assuming you've been doing your diligence work of creating a ruby project according to the lambda guidelines on Amazon (https://docs.aws.amazon.com/lambda/latest/dg/lambda-ruby.html) it's a matter of creating a Gemfile and in here add the gem mysql2.

An example of what you're looking for might be like this.

require 'json'
require 'mysql2'

$client = Mysql2::Client.new(
  host: ENV["DB_HOST"],
  username: ENV["DB_USER"],
  password: ENV["DB_PASSWORD"],
  database: ENV["DB_NAME"],
  port: ENV["DB_PORT"]
)

def lambda_handler(event:, context:)
  # Add your query here
  results = $client.query("SELECT * FROM items;").to_a

  {
    statusCode: 200,
    body: results.to_json
  }
end
like image 119
Paco V. Avatar answered Aug 15 '26 10:08

Paco V.