I have wrote an AWS lambda function in python to access my mysql instance in RDS. The mysql instance is in the same region as the AWS lambda function and was assigned a default VPC.
The following is the python handler code, with an error printing out: “ERROR: Unexpected error: Could not connect to MySql instance”. The handler is “mysql_test”. I am new to serverless.com. Would you guys please help me in this issue since it is very urgent and important for our business to migrate from the traditional architecture to serverless framework. Thanks!
import sys
import logging
import pymysql
name = "xxxx"
password = "xxxxxxxxxx"
db_name = "xxxxxxxxxx"
rds_host = "xxxxxxxxxxxx.us-west-2.rds.amazonaws.com"
port = 3306
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 mysql_test(event, context):
** “”"**
** This function inserts content into 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)**
** response = {**
** “statusCode”: 200,**
** “body”: “Added %d items to RDS MySQL table” %(item_count)**
** }**
** return response**
Best,
Michael