Looking for example lambda functions for Aurora Serverless v2

0

Aurora MySQL serverless 1 is no longer supported (for creation), yet all of the documentation is still pointing towards serverless v1. I am using MySQL serverless v2 with secrets manager and I have a python module that is able to connect to the writer endpoint alright without RDS proxy. For following the lambda function examples, I have created an RDS proxy, however I am finding a hard time finding reliable lambda code examples, especially in javascript that can successfully connect to my Aurora serverless v2. The goal is to have this connection be triggered by cognito events.

1 Answer
0

Hi,

Below is a sample code,

const AWS = require('aws-sdk');
const rdsDataService = new AWS.RDSDataService();

exports.handler = async (event, context) => {
    // Set the SQL statement
    const sql = 'SELECT * FROM my_table';

    // Execute the SQL statement
    const params = {
        database: 'my_database',
        resourceArn: 'arn:aws:rds:us-east-1:123456789012:cluster:my-cluster',
        secretArn: 'arn:aws:secretsmanager:us-east-1:123456789012:secret:my-secret',
        sql: sql
    };
    const response = await rdsDataService.executeStatement(params).promise();

    // Return the query results as a JSON string
    const body = JSON.stringify(response.records);
    const statusCode = 200;
    return { statusCode, body };
};

Hope this helps

AWS
Arun
answered a year ago
  • Hi Arun, thanks for the code example. This brings the same error:

    {"errorType":"BadRequestException","errorMessage":"HttpEndpoint is not enabled for cluster
    

    since serverless v2 has no support for Data API. Hence, the need for code example using RDS proxy endpoint alongside secrets manager.

    Thanks again!

  • Sure. can you try importing pg8000 to create a pg8000.connect object to connect to the DB. A code sample with teh same is below

    import boto3 import pg8000

    def lambda_handler(event, context): rds_data = boto3.client('rds-data') response = rds_data.execute_statement( resourceArn='arn:aws:rds:us-east-1:123456789012:cluster:my-db-cluster', secretArn='arn:aws:secretsmanager:us-east-1:123456789012:secret:my-db-secret', database='my-db-name', sql='SELECT * FROM my_table;' )

    conn = pg8000.connect(
        host=response['records'][0][0]['stringValue'],
        port=5432,
        database='my-db-name',
        user='my-db-user',
        password='my-db-password'
    )
    
    cursor = conn.cursor()
    cursor.execute('SELECT * FROM my_table')
    rows = cursor.fetchall()
    
    for row in rows:
        print(row)
    
    cursor.close()
    conn.close()
    

    Try and let us know, if it works

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions