Learn how to access an RDS from a Lambda function written in Python.
There is a tutorial in the official AWS documentation, so follow it. However, in the tutorial, the operation is based on CLI, so we will replace it with the operation from the mannequin as appropriate.
-Tutorial: Set up an Lambda function to access Amazon RDS on Amazon VPC
Let's take a closer look step by step.
Create an RDS from the AWS mannequin. It will take some time to create. Once you've created it, make sure you can access it locally.
$ mysql -u username -h lambda.xxxxxxxxxxxx.us-east-1.rds.amazonaws.com -p
When you create an RDS, the security group settings default to restricted sources. Therefore, even if you can access it from your local environment, you will not be able to access it from Lambda after that. Therefore, edit the security group of the relevant RDS instance and change the source to any IP (0.0.0.0/0). (Set an appropriate IP according to your requirements.)
Suppose you are currently working on / path / to / workdir /
.
Please read / path / to / workdir /
as appropriate.
Create a Python script similar to the following. The file name is ʻapp.py`.
import sys
import logging
import rds_config
import pymysql
#rds settings
rds_host = "rds-instance-endpoint"
name = rds_config.db_username
password = rds_config.db_password
db_name = rds_config.db_name
logger = logging.getLogger()
logger.setLevel(logging.INFO)
try:
conn = pymysql.connect(rds_host, user=name, passwd=password, db=db_name, connect_timeout=5)
except:
logger.error("ERROR: Unexpected error: Could not connect to MySql instance.")
sys.exit()
logger.info("SUCCESS: Connection to RDS mysql instance succeeded")
def handler(event, context):
"""
This function fetches content from mysql RDS instance
"""
item_count = 0
with conn.cursor() as cur:
cur.execute("create table Employee3 ( EmpID int NOT NULL, Name varchar(255) NOT NULL, PRIMARY KEY (EmpID))")
cur.execute('insert into Employee3 (EmpID, Name) values(1, "Joe")')
cur.execute('insert into Employee3 (EmpID, Name) values(2, "Bob")')
cur.execute('insert into Employee3 (EmpID, Name) values(3, "Mary")')
conn.commit()
cur.execute("select * from Employee3")
for row in cur:
item_count += 1
logger.info(row)
#print(row)
return "Added %d items from RDS MySQL table" %(item_count)
In ʻapp.py,
rds_configand
pymysql` are imported, so prepare them.
First, save the following contents as rds_config.py
.
#config file containing credentials for rds mysql instance
db_username = "username"
db_password = "password"
db_name = "databasename"
Then use pip to save pymysql
to/ path / to / workdir /
.
$ pip install pymysql -t /path/to/workdir/
Now that you have the files you need, zip them up.
The caveat here is that instead of archiving the entire directory, archive under / path / to / workdir /
.
$ zip -r app.zip /path/to/workdir/*
Here, I created a zip file called ʻapp.zip`.
Create a new role on the AWS IAM screen. At that time, select ʻAWS Lambda` as the AWS service role. Here we name it'lambda-role'.
Create a Lambda function from your AWS mannequin.
This time I chose Blank Function
and API Gateway as the trigger.
Please select the necessary ones in this area.
Other setting items are as follows.
Create a Lambda function with this setting.
Finally, run it manually.
You can do it manually by pressing the Test
button on the Lambda screen.
If you get the following results, you are successful.
"Added 3 items from RDS MySQL table"
Recommended Posts