Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in AWS by (19.1k points)

I am trying to connect AWS Lambda function to RDS mysql database.

I just wanted to update the database from my lambda function. Is it possible to access RDS by specifying the IAM Role and access Policy?.

I can connect to mysql database using mysql client.but when I try on lambda I can't do that. here is my code.

console.log('Loading function');

var doc = require('dynamodb-doc');

var dynamo = new doc.DynamoDB();

var mysql = require('mysql');

exports.handler = function(event, context) {

    //console.log('Received event:', JSON.stringify(event, null, 2));  

    var operation = event.operation;

    delete event.operation;

    switch (operation) {

        case 'create':

            var conn = mysql.createConnection({

                host: 'lamdatest.********.rds.amazonaws.com', // RDS endpoint 

                user: 'user', // MySQL username 

                password: 'password', // MySQL password 

                database: 'rdslamda'

            });

            conn.connect();

            console.log("connecting...");

            conn.query('INSERT INTO login (name,password) VALUES("use6","password6")', function(err, info) {

                console.log("insert: " + info.msg + " /err: " + err);

            });

            console.log("insert values in to database");

            break;

        case 'read':

            dynamo.getItem(event, context.done());

            break;

        default:

            context.fail(new Error('Unrecognized operation "' + operation + '"'));

    }

    context.succeed();

};

1 Answer

0 votes
by (44.4k points)

You can access the RDS MySQL instance from a Lambda function. Use this open-source node-mysql library:

https://github.com/mysqljs/mysql

You can now put them in a subnet inside your VPC and access them from there. To do that, your subnet needs enough free IP addresses because if Lambda’s scaling. Also, if the Lambda function requires internet access, you will have to include an Internet Gateway to it.

Access Resources in a VPC from Your Lambda Functions

You can get more information about this AWS computing service by reading AWS Lambda.

Related questions

Want to get 50% Hike on your Salary?

Learn how we helped 50,000+ professionals like you !

0 votes
1 answer

Browse Categories

...