Connect to MySql

i wonder how to use mysql rds on serverless ?
ive alreadey npm install mysql and setting up like default but error come out…

const mysql = require(‘mysql’);

let con = mysql.createConnection({
host : “xxxxx”,
user : “xxxx”,
password : “xxxx”,
database : “xxxx”
});

con.connect();
module.exports = con;`

ive already done this… any one know how to setting this up? Or
is serverless v1 just support dynamoDB and dont support node_module ?

Does that code work on your local system as well? Here is also the guide for it: http://docs.aws.amazon.com/lambda/latest/dg/vpc-rds.html

You might need to put the functions into a VPC: https://serverless.com/framework/docs/providers/aws/vpc/

thanks for reply @flomotlik,:grin:
if i am use it on local (without serverless) it work fine…
so i need vpc to work with RDS ?
and just add this?

vpc:
securityGroupIds:
- securityGroupId1
- securityGroupId2
subnetIds:
- subnetId1
- subnetId2

but is serverless v1 not support nodeModule ?

If you can connect from your local system into RDS then it should be working from the lambda as well I think. We do support any database or pretty much any service that AWS provides and also node_modules. Basically if it works in NodeJS it should work in Lambda with Serverless.

so serverless already support it, so, if i not wanna use vpc… i can still use RDS right ?
is it something i must include on .yml file to getting node_module ?

@frengkys There are a few of places this could be going wrong. I’d start by making sure you have a working Lambda function that at least attempts to create a connection. console.log() and the CloudWatch logs will help you.

Also see https://aws.amazon.com/blogs/aws/new-access-resources-in-a-vpc-from-your-lambda-functions/ for information on running Lambda functions inside your VPC. You’ll need to do that unless your database port is open to the world (a bad idea)

If you’re still stuck then please post your entire Lambda function here. The code you’ve posted so far won’t run on it’s own.

hiiii, thanks for replying… this is my code

'use strict';

const mysql = require('mysql');

let con = mysql.createConnection({
    host : "xxxxxxxxxxxxxxxxxxxx",
    user : "xxxxxxxx",
    password : "xxxxxxx",
    database : "xxxxxxxx",
    });
con.connect();

module.exports.send =  function (event, context, callback){

  let data = event.body.json_data;

  const response = {
    statusCode: 200,
    body: JSON.stringify({
      Message: data.hello_world,
    })
  };
  context.succeed(response)
};

and the output is {“statusCode”:500,“body”:{“errorMessage”:“Process exited before completing request”}

and .yml is like this

functions:
  hello:
    handler: handler.send
    events:
    - http:
       method: POST
       path: send
       integration: lambda

What does the cloud watch log say? It should contain more information about the error.

sorry, but how can i use cloud watch log on serverless?

I guess you should close the connection using con.destroy(); before calling context.succeed but the log in CloudWatch should tell you more. Locate the function in aws console, go to Monitoring tab and follow link “View logs in CloudWatch”

i dont know why but the sql wont connect…
the error went gone but the sql wont connected
this is my code now

'use strict';

const mysql =require('mysql');

const con = mysql.createConnection({
    host : "xxxxxxxxxxxxxxxxxxxx",
    user : "xxxxxxxx",
    password : "xxxxxxxxxx",
    database : "xxxxxxxxx",
  });

  con.connect(function(err){
        if (err){ throw err
          console.log('-------------------- Error connect to DB --------------------');
          return;
        }
          console.log('-------------------- DB is connected ! ----------------------');
    });

module.exports.send =  (event, context, callback) => {
  var data = event.body.json_data;

  console.log("pre");
  con.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
  if (err) throw err;

     console.log('The solution is: ', rows[0].solution);
  });
  console.log("post");

  con.query('SELECT * FROM `temp` ',function (error, results, fields) {
      console.log(results);
    });

  var temp = {name : "frengky"};
  var query = con.query('INSERT INTO `temp` SET ?', temp,function(err,res){
      if(err) throw err ;
    });
  console.log(query.sql);

  con.end();

  const response = {
    statusCode: 200,
    body: JSON.stringify({
      data : data
    }),
  };
  context.succeed(response);
};

@buggy @flomotlik @JakubMatejka

And what do the logs say? BTW. regarding your RDS setup, do you have it publicly accessible?

there is nothing on the logs seriously…

it should be
’-------------------- Error connect to DB -------------------- or -------------------- DB is connected ! ---------------------- right?
but none of them shown…

but the ‘pre’ and ‘post’ logs is shown

and publicly accessible is already yes

You database connection code is outside of the Lambda function handler. I wouldn’t assume that it’s being run every time the Lambda is called.

Try moving the const con = mysql.createConnection(...) and con.connect(...) inside the Lambda handler function so that you know it’s actually being run.

Yes, the container could have been reused which means that the code outside of module.exports handler wasn’t run again (https://aws.amazon.com/blogs/compute/container-reuse-in-lambda/).

Second thing is that console.log of the error won’t be called at all because you throw the error before, right?

‘use strict’;

module.exports.send = (event, context, callback) => {
const mysql =require(‘mysql’);

const con = mysql.createConnection({
host : “xxxxxxxxxxxxxxx”,
user : “xxxxxxxxx”,
password : “xxxxxxxxxxx”,
database : “xxxxxxx”,
});

con.connect(function(err){
if (err){
console.log(’-------------------- Error connect to DB --------------------’);
return;
}
console.log(’-------------------- DB is connected ! ----------------------’);
});
var data = event.body.json_data;

console.log(“pre”);
con.query(‘SELECT 1 + 1 AS solution’, function(err, rows, fields) {
if (err) throw err;

 console.log('The solution is: ', rows[0].solution);

});
console.log(“post”);

var temp = {name : “frengky”};
var query = con.query(‘INSERT INTO temp SET ?’, temp,function(err,res){
if(err) throw err ;
});
console.log(query.sql);

con.end();

const response = {
statusCode: 200,
body: JSON.stringify({
id : data.id,
}),
};
context.succeed(response);
};

module.exports.ping = (event, context, callback) => {
const response = {
statusCode: 200,
body: JSON.stringify({
message: ‘ping handler called!’,
}),
};

context.succeed(response);
};

the logs still isnt say anything except ‘pre’ and ‘post’ log… oh and console.log(query.sql)
but the logs that say Mysql is connected or not isn’t shown…
@buggy @JakubMatejka

service: mytest

provider:
name: aws
runtime: nodejs4.3

stage: dev
region: ap-southeast-2

functions:
sendData
handler: handler.send
memorySize: 128
timeout: 10
events:
- http:
method: POST
path: send
integration: lambda
cors: true
response:
headers:
Access-Control-Allow-Origin: “*”

ping:
handler: handler.ping
memorySize: 128
timeout: 10
events:
- http:
method: GET
path: ping

resources:
Resources:
AWSLambdaVPCAccessExecutionRole:
Type: AWS::IAM::ManagedPolicy
Properties:
Description: Policy for allowing vpc connection.
Roles:

  • {“Ref” : “IamRoleLambdaExecution”}
    PolicyDocument:
    Statement:
    Effect: Allow
    Action:
  • “dynamodb:*”
  • “kinesis:*”
  • “s3:*”
  • “rds:*”
  • “ec2:*”
  • “cloudformation:"
    Resource: "

or are there something forgotten on my .yml file? @buggy @JakubMatejka @flomotlik