How to Use AWS Lambda Function to Access an Amazon RDS Database?
Last Updated :
16 Apr, 2024
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.
.png)
- Select the database engine you want to use. We have selected mysql as engine.
- Specify instance name and size in next section.
.png)
- Add username and password for the database.
.png)
- 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.
.png)
- Specify function name for lambda function.
- On this page specify details for RDS Proxy. Create new proxy and specify username and password for DB.
.png)
- 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.
.jpg)
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.
.jpg)
- Once the environment is changed. Go to configuration tab and setup environment variables to be used by function.
.png)
- 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
.png)
- 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.
.png)
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.
.png)
- Once the event is created click on Test.
- Function should start execution and you should see below output.
.jpg)
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.
.png)
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.