Search code examples
javascriptnode.jsvisual-studio-codeaws-lambdasam

Trying to build lambda function using SAM plugin in visual studio code and trying to connect to MYSQL RDS instance but not working


I am building lambda function using visual studio code SAM option. I am trying to connect to RDS instance (MYSQL) which is in VPC network. I tried connecting using following code. I am not getting any error but it is not connecting to DB. I have searched every where but didn't get any solution. I tried following but didn't worked

const fs = require('fs');


    const mysqlssh = require('mysql-ssh');
    mysqlssh.connect(
        {
            host: 'XXX.XXX.XX.XX',
            user: 'ec2-user',
            privateKey: fs.readFileSync('./XXXX-txlarge.pem')
        },
        {
            host: '-staging-instanceXXXXX.rds.amazonaws.com',
            user: 'user',
            password: 'password',
            database: 'db'
        }
    )
    .then(client => {
        client.query('SELECT * FROM users', function (err, results, fields) {
            if (err) throw err
            console.log(results);
            mysqlssh.close()
        })
    })

Solution

  • Instead of using mysql-ssh which is tunneling based type of sql connection module try to use simple mysql module,

    const fs = require('fs');   
    
    const mysql = require('mysql');
    let connection = mysql.createConnection(
        {
            host: 'XXX.XXX.XX.XX-staging-instanceXXXXX.rds.amazonaws.com',
            user: 'user',
            password: 'password',
            database: 'db'
        }
    );
    
     connection.connect();
    
     connection.query('SELECT * FROM users', function (err, results, fields) {
           if (err) throw err
            console.log("rows: " + rows);
            context.succeed('Success');
        });
    

    PS: You might need to some of code as per you needs, but this is what you should try doing.