AWS Lambda RDS
Here are the steps for giving your Lambda function the ability to access an RDS MySQL instance in the VPC.
Step One: Creating Execution Role
To create the execution role which grants your function permission for accessing AWS resources, follow the steps below.
For creating an execution role
- Head straight to the roles page which is in the IAM console.
- Click on Create role.
- Go ahead and start creating a role having the below states properties.
- Role name: lambda-vpc-role.
- Trusted entity: Lambda.
- Permissions: AWSLambdaVPCAccessExecutionRole.
AWSLambdaVPCAccessExecutionRole – includes permissions for the function to start managing network connections to a VPC.
Step Two: Creating an AWS RDS database instance
In the following steps, we will be creating with the example Lambda function a table named Employee, enter a couple of records, then retrieve those records.
The table which will be created by the Lambda function includes the below schema:
Employee(EmpID, Name)
EmpID refers to the primary key. Currently, you must add a couple of new records to the table.
Firstly, an RDS MySQL instance needs to be launched in the default VPC with ExampleDB database. In case you possess an RDS MySQL instance which runs in your default VPC, you should ignore this step.
An RDS MySQL instance may be launched through 1 of the below methods:
- Go over the steps for creating a MySQL DB instance then going ahead with connecting it to a database on a MySQL DB instance.
- Utilize the below mentioned CLI command:
$ aws rds create-db-instance –db-name ExampleDB –engine MySQL \
–db-instance-identifier MySQLForLambdaTest –backup-retention-period 3 \
–db-instance-class db.t2.micro –allocated-storage 5 –no-publicly-accessible \
–master-username username –master-user-password password
Type in the name of the database, the name of the user name, and its password. A host address of the DB instance is required, and it’s given to you through the RDS console. You may possibly require to keep waiting for the instance status to become available as well as for the Endpoint value to show up in the console.
Step Three: Creating deployment package
In the below example Python code you can run a SELECT query over the table of Employee in the MySQL RDS instance which you had created in the VPC. A table will be created using the code in the ExampleDB database, sample records will be added and retrieved.
Example 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 pymysql.MySQLError as e:
logger.error(“ERROR: Unexpected error: Could not connect to MySQL instance.”)
logger.error(e)
sys.exit()
logger.info(“SUCCESS: Connection to RDS MySQL instance succeeded”)
def handler(event, context):
“””
This function gets you specific content from MySQL RDS instance
“””
item_count = 0
with conn.cursor() as cur:
cur.execute(“create table Employee ( EmpID int NOT NULL, Name varchar(255) NOT NULL, PRIMARY KEY (EmpID))”)
cur.execute(‘insert into Employee (EmpID, Name) values(1, “Joe”)’)
cur.execute(‘insert into Employee (EmpID, Name) values(2, “Bob”)’)
cur.execute(‘insert into Employee (EmpID, Name) values(3, “Mary”)’)
conn.commit()
cur.execute(“select * from Employee”)
for row in cur:
item_count += 1
logger.info(row)
#print(row)
conn.commit()
return “Added %d items from RDS MySQL table” %(item_count)
When you execute pymysql.connect() outside of the handler your function will be able to use the database connection once again for a more enhanced performance.
Another file will include connection data regarding the function.
Example rds_config.py
#config file containing credentials for RDS MySQL instance
db_username = “username”
db_password = “password”
db_name = “ExampleDB”
Dependencies
- pymysql –This library is utilized by the lambda function for accessing the MySQL instance.
Start installing dependencies using Pip then creating a deployment package.
Step Four: Creating Lambda function
Go ahead with creating your Lambda function using the create-function command.
$ aws lambda create-function –function-name CreateTableAddRecordsAndRead –runtime python3.8 \
–zip-file fileb://app.zip –handler app.handler \
–role arn:aws:iam::123456789012:role/lambda-vpc-role \
–vpc-config SubnetIds=subnet-0532bb6758ce7c71f,subnet-d6b7fda068036e11f,SecurityGroupIds=sg-0897d5f549934c2fb
Step Five: Testing Lambda function
Now, you need to start invoking the Lambda function manually through the invoke command. Upon executing the Lambda function, it is going to run the SELECT query over the Employee table in the RDS MySQL instance then print the results that will be sent to CloudWatch Logs.
- Start by invoking the Lambda function using the invoke command.
$ aws lambda invoke –function-name CreateTableAddRecordsAndRead output.txt
- Make sure that the Lambda function had been executed in a successful way through doing the following:
- Check the output.txt file.
- Go over the results found in the Lambda console.
- Make sure of the results in CloudWatch Logs.
After finally creating a Lambda function which is capable of accessing a database found in your VPC, you will be able to invoke this function invoked in response to events.