This project shows how to manipulate a database table in MySQL from an AWS Lambda function. The MySQL instance is hosted using Amazon Relational Database Service (RDS). AWS Lambda function is written using Java and packaged using Maven. Serverless Application Model (SAM) is used to deploy the Lambda function. AWS CLI is used to invoke the function.
-
Create RDS instance
aws rds create-db-instance \ --db-instance-identifier LambdaMySQLTest \ --db-instance-class db.r3.large \ --engine MySQL \ --port 3006 \ --allocated-storage 5 \ --db-name ExampleDB \ --master-username master \ --master-user-password master123 \ --backup-retention-period 3
-
Create inbound role for the security group:
-
Get security group id:
aws rds describe-db-instances | jq ".DBInstances[].VpcSecurityGroups[].VpcSecurityGroupId"
-
Add inbound role:
aws ec2 authorize-security-group-ingress --group-id <group-id> --protocol all --port 3006 --cidr 0.0.0.0/0
-
-
Get instance id:
aws rds describe-db-instances | jq ".DBInstances[0].Endpoint.Address"
-
Install MySQL client:
brew install mysql
-
Create a table and add some rows
mysql -h <endpoint> -P 3306 -u master -pmaster123
:mysql: [Warning] Using a password on the command line interface can be insecure. Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 43 Server version: 5.6.35-log MySQL Community Server (GPL) Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. mysql> use ExampleDB; Database changed mysql> CREATE TABLE EMPLOYEE(id int NOT NULL, name VARCHAR(20), PRIMARY KEY(id)); Query OK, 0 rows affected (0.03 sec) mysql> INSERT INTO EMPLOYEE (id, name) VALUES (1, "Penny"); Query OK, 1 row affected (0.02 sec) mysql> INSERT INTO EMPLOYEE (id, name) VALUES (2, "Sheldon"); Query OK, 1 row affected (0.02 sec) mysql> INSERT INTO EMPLOYEE (id, name) VALUES (3, "Leonard"); Query OK, 1 row affected (0.02 sec) mysql> INSERT INTO EMPLOYEE (id, name) VALUES (4, "Howard"); Query OK, 1 row affected (0.02 sec) mysql> INSERT INTO EMPLOYEE (id, name) VALUES (5, "Raj"); Query OK, 1 row affected (0.02 sec) mysql> INSERT INTO EMPLOYEE (id, name) VALUES (6, "Amy"); Query OK, 1 row affected (0.02 sec) mysql> INSERT INTO EMPLOYEE (id, name) VALUES (7, "Bernadette"); Query OK, 1 row affected (0.02 sec) mysql> exit; Bye
-
Create a package:
mvn package
-
Upload to S3:
mvn install
-
Deploy Lambda:
aws cloudformation deploy --template-file app.yml --stack-name employee
-
Invoke Lambda:
aws lambda invoke \ --function-name Employee \ --payload '{ "id": 10, "name": "Smith" }' \ employee.out
-
Delete Lambda:
aws cloudformation delete-stack --stack-name employee