AWS Lambda 可以连接到 RDS mySQL 数据库并更新数据库吗? [英] can AWS Lambda connect to RDS mySQL database and update the database?
问题描述
我正在尝试将 AWS Lambda 函数连接到 RDS mysql 数据库.
我只想从我的 lambda 函数更新数据库.是否可以通过指定 IAM 角色和访问策略来访问 RDS?.
我可以使用 mysql 客户端连接到 mysql 数据库.但是当我尝试使用 lambda 时,我不能这样做.这是我的代码.
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 specifiying IAM Role and access Policy?.
I can connect to mysql databse 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();
};
推荐答案
是的.您可以从 AWS Lambda 访问 MySql RDS 数据库.
Yes. You can access a MySql RDS database from AWS Lambda.
您可以使用 node-mysql
库.
但是,有一个很大的警告伴随它.
However, there is a big caveat that goes with it.
AWS Lambda(目前)无权访问 VPC 内的私有子网.因此,为了让 AWS Lambda 能够访问您的 RDS 数据库,它必须是可公开访问的,这可能会给您带来安全风险.
AWS Lambda does not (currently) have access to private subnets inside a VPC. So in order for AWS Lambda to access your RDS database, it must be publicly accessible, which could be a security risk for you.
更新 (2015-10-30):AWS Lambda 宣布即将推出 VPC 支持 (自 re:Invent 2015 起),所以这不会成为问题.
Update (2015-10-30): AWS Lambda announced upcoming VPC support (as of re:Invent 2015), so this won't be an issue for much longer.
更新 (2015-11-17):AWS Lambda 仍然不支持 VPC.
Update (2015-11-17): AWS Lambda still does not have VPC support.
更新 (2016-02-11):AWS Lambda 现在可以访问 VPC 资源了:
Update (2016-02-11): AWS Lambda can now access VPC resources:
https://aws.amazon.com/blogs/aws/new-access-resources-in-a-vpc-from-your-lambda-functions/
为了实现此功能,您的 Lambda 函数实际上将在子网中的 VPC 内执行.此功能有一些注意事项:
To achieve this functionality, your Lambda function will actually execute inside your VPC in a subnet. Some caveats come with this functionality:
- VPC 子网需要足够的免费 IP 地址来处理 Lambda 的扩展
- 如果您的 Lambda 函数需要访问互联网,那么它的指定 VPC 子网将需要互联网网关或 NAT
这篇关于AWS Lambda 可以连接到 RDS mySQL 数据库并更新数据库吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!