简体   繁体   中英

Unable to query RDS MySQL from AWS Lambda using Node JS

I am trying to query MySQL RDS from Lambda using Node js mysql client. The same code works normally in local.

var mysql = require('mysql');

// TODO Read credentials from Secret Manager. 
var connection = mysql.createConnection({
    host: "XXX",
    user: "XXX",
    password: "XXX",
    database: "XXX",
    timezone: 'utc'
});

connection.connect();

exports.handler = async (event, context, callback) => {

    connection.query('show tables', function (error, results, fields) {
        if (error) {
            connection.destroy();
            throw error;
        } else {
            // connected!
            console.log(results);
            callback(error, results);
            connection.end(function (err) { callback(err, results); });
        }
    });
};

When I execute lambda I neither get error nor results

  1. Both RDS and Lambda are on same VPC
  2. Increased Lambda timeout to 5 minutes
  3. Gave the below permissions to Lambda role

AWSLambdaExecute
AWSLambdaBasicExecutionRole
AWSLambdaVPCAccessExecutionRole
AWSLambda_FullAccess

  1. Modified RDS security group to allow lambda.

Found the solution here - https://stackoverflow.com/a/64739725/5589444

After removing the async keyword it worked. below is the updated code

var mysql = require('mysql');

// TODO Read credentials from Secret Manager. 
var connection = mysql.createConnection({
    host: "XXX",
    user: "XXX",
    password: "XXX",
    database: "XXX",
    timezone: 'utc'
});

connection.connect();

exports.handler = (event, context, callback) => {

    connection.query('show tables', function (error, results, fields) {
        if (error) {
            connection.destroy();
            throw error;
        } else {
            // connected!
            console.log(results);
            callback(error, results);
            connection.end(function (err) { callback(err, results); });
        }
    });
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM