Open In App

How to Use AWS Lambda Function to Access an Amazon RDS Database?

Last Updated : 16 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

AWS lambda is a managed serverless deployment service of AWS which can be used for implementation of various applications in cloud. AWS RDS is relational database management system that supports various vendors. In this article we will see how we can create and access Amazon RDS database through a lambda function.

What is AWS Lambda?

AWS Lambda Functions are serverless components that execute code only when the particular trigger is invoked. the trigger for functions has to configured as requirement. various triggers such as HTTP, S3 object upload, message queues are supported by AWS Lambda. AWS Lambda reduces cost for idle infrastructure.

What is Amazon RDS?

It is a managed relational database service provided by AWS. It allows creation, managing and updating of database engine and infrastructure. Various engines are supported such as PostgreSQL, MySQL, Aurora etc. It is a highly scalable and secured database service.

Understanding Of Primary Terminologies

  • AWS Lambda Function: It is a serverless compute component that allows execution of code only when invoked without provision of servers.
  • Function Trigger: It is an event that invokes lambda function and executes it. For e.g. HTTP Trigger, Message queues etc.
  • Lambda handler: It is a function that accepts event that invoked lambda function and executes code mentioned in function.
  • Amazon RDS Database: Managed Relational Database service provided AWS.
  • RDS Proxy: Endpoint used to allow secure connection to RDS instance.

Access RDS Using AWS Lambda Function: A Step-By-Step Guide

Step 1: Setup Amazon RDS Instance

  • On AWS home page search for RDS and click on create new instance from overview page.
  • Now specify creation method. For this article we will be using Easy Create. For additional options use standard creation.

Choose DB creation Method

  • Select the database engine you want to use. We have selected mysql as engine.
  • Specify instance name and size in next section.

Choosing DB Instance Size

  • Add username and password for the database.

Specify The Credentials

  • Once everything is reviewed click on create database. Wait for the database to be completely created and its status is available.

Step 2: Setup Lambda Connection For RDS

  • Once the DB is available click on actions tab and then select Setup Lambda Connection.

Connect RDS To Lambda

  • Specify function name for lambda function.
  • On this page specify details for RDS Proxy. Create new proxy and specify username and password for DB.

Creating New Proxy

  • Click on create and wait for successful creation of Proxy and function.
  • Once the proxy is created successfully. Go to proxies tab and copy proxy endpoint.

Copying The Endpoints

Step 3: Configure Lambda Function For Access

  • Now go to lambda function overview page that is created in previous step.
  • On this page change execution environment from NodeJS to Python as below.

Configure Lambda Function For Access

  • Once the environment is changed. Go to configuration tab and setup environment variables to be used by function.

Provide Configurations In Environment Variables

  • Now locally create file called index.py inside an empty directory which will contain code for accessing the Database.
  • the code will look like below.
Python
#index.py

import sys
import logging
import pymysql
import json
import os

user_name = os.environ['DB_USER']
password = os.environ['DB_PASSWORD']
rds_proxy_host = os.environ['DB_HOST']
db_name = os.environ['DB_NAME']

logger = logging.getLogger()
logger.setLevel(logging.INFO)

try:
    conn = pymysql.connect(host=rds_proxy_host, user=user_name, passwd=password, db=db_name, connect_timeout=5)
except pymysql.MySQLError as e:
    logger.error("ERROR: Unexpected error: Could not connect to MySQL instance.")
    logger.error(e)
    sys.exit(1)



def handler(event, context):
    if(conn):
        logger.info("SUCCESS: Connection to RDS for MySQL instance succeeded")
        return "Connection is successful";
  • Install PyMYSQL package which is required by code for accessing DB.
pip install --target . pymysql

Installing PyMYSQL

  • Now zip both code and pymysql package folder together. On lambda functions code editor click on upload from zip.
  • Select the created zip and click on save. The fuction should be updated automatically with the changes.

Uploading Files

Step 4: Test The Function For Access

  • Click on Test from code editor of lambda function. It will open event creation page.
  • Give any name to the event and leave everything as default and proceed.

Configuring Test Events

  • Once the event is created click on Test.
  • Function should start execution and you should see below output.

Triggering The LambdaFunction

Step 5: Access Logs For The Function To View Console Outputs

  • On Function overview page open monitor tab.
  • Click on view in CloudWatch which will redirect to CloudWatch logs.
  • Click on latest log stream and you should see logs as below from function execution.

Accessing Logs

Conclusion

Thus, we have seen how to access Amazon RDS database from AWS Lambda function. We have created connection to the Amazon RDS database. Lambda Function can be further configured for performing queries on database tables.

AWS Lambda And Amazon RDS Database – FAQ’s

How Can I Use AWS Lambda To Access An Amazon RDS Database?

You can use AWS Lambda to access an Amazon RDS database by writing a Lambda function that connects to the database and executes SQL queries or commands. You can use the AWS SDKs or libraries specific to your programming language to establish a connection to the database and perform CRUD (Create, Read, Update, Delete) operations.

What Permissions Does My Lambda Function Need To Access An RDS Database?

Your Lambda function will need appropriate permissions to access the RDS database. You can create an IAM (Identity and Access Management) role with the necessary permissions, such as rds:Connect, rds:ExecuteStatement, and rds:DescribeDBInstances, and then assign this role to your Lambda function.

How Do I Handle Database Connections In My Lambda Function?

It’s important to manage database connections efficiently in your Lambda function to minimize latency and resource consumption. You can establish a database connection outside of the Lambda handler function and reuse it for multiple invocations using techniques such as connection pooling or keeping the connection alive between invocations.

Can I Use Environment Variables To Store Database Connection Details In My Lambda Function?

Yes, you can use environment variables to store sensitive information such as database connection strings, usernames, and passwords in your Lambda function. This allows you to securely pass configuration values to your function without hardcoding them in your code.

How Do I Handle Errors And Retries When Accessing An Rds Database From A Lambda Function?

You should implement error handling and retry logic in your Lambda function to handle transient errors, such as network timeouts or database connection failures. You can use built-in retry mechanisms provided by the AWS SDKs or implement custom retry logic with exponential backoff to retry failed operations with increasing delays between retries.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads