You can connect a Lambda function to an Amazon Relational Database Service (Amazon RDS) database directly and through an Amazon RDS Proxy. Direct connections are useful in simple scenarios, and proxies are recommended for production. A database proxy manages a pool of shared database connections which enables your function to reach high concurrency levels without exhausting database connections.
We recommend using Amazon RDS Proxy for Lambda functions that make frequent short database connections, or open and close large numbers of database connections. For more information, see Automatically connecting a Lambda function and a DB instance in the Amazon Relational Database Service Developer Guide.
Tip
To quickly connect a Lambda function to an Amazon RDS database, you can use the in-console guided wizard. To open the wizard, do the following:
Open the Functions page
of the Lambda console. -
Select the function you want to connect a database to.
-
On the Configuration tab, select RDS databases.
-
Choose Connect to RDS database.
After you've connected your function to a database, you can create a proxy by choosing Add proxy.
Configuring your function to work with RDS resources
In the Lambda console, you can provision, and configure, Amazon RDS database instances and proxy resources. You can do this by navigating to RDS databases under the Configuration tab. Alternatively, you can also create and configure connections to Lambda functions in the Amazon RDS console. When configuring an RDS database instance to use with Lambda, note the following criteria:
-
To connect to a database, your function must be in the same Amazon VPC where your database runs.
-
You can use Amazon RDS databases with MySQL, MariaDB, PostgreSQL, or Microsoft SQL Server engines.
-
You can also use Aurora DB clusters with MySQL or PostgreSQL engines.
-
You need to provide a Secrets Manager secret for database authentication.
-
An IAM role must provide permission to use the secret, and a trust policy must allow Amazon RDS to assume the role.
-
The IAM principal that uses the console to configure the Amazon RDS resource, and connect it to your function must have the following permissions:
Note
You need the Amazon RDS Proxy permissions only if you configure an Amazon RDS Proxy to manage a pool of your database connections.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ec2:CreateSecurityGroup",
"ec2:DescribeSecurityGroups",
"ec2:DescribeSubnets",
"ec2:DescribeVpcs",
"ec2:AuthorizeSecurityGroupIngress",
"ec2:AuthorizeSecurityGroupEgress",
"ec2:RevokeSecurityGroupEgress",
"ec2:CreateNetworkInterface",
"ec2:DeleteNetworkInterface",
"ec2:DescribeNetworkInterfaces"
],
"Resource": "*"
},
{
"Effect": "Allow",
"Action": [
"rds-db:connect",
"rds:CreateDBProxy",
"rds:CreateDBInstance",
"rds:CreateDBSubnetGroup",
"rds:DescribeDBClusters",
"rds:DescribeDBInstances",
"rds:DescribeDBSubnetGroups",
"rds:DescribeDBProxies",
"rds:DescribeDBProxyTargets",
"rds:DescribeDBProxyTargetGroups",
"rds:RegisterDBProxyTargets",
"rds:ModifyDBInstance",
"rds:ModifyDBProxy"
],
"Resource": "*"
},
{
"Effect": "Allow",
"Action": [
"lambda:CreateFunction",
"lambda:ListFunctions",
"lambda:UpdateFunctionConfiguration"
],
"Resource": "*"
},
{
"Effect": "Allow",
"Action": [
"iam:AttachRolePolicy",
"iam:AttachPolicy",
"iam:CreateRole",
"iam:CreatePolicy"
],
"Resource": "*"
},
{
"Effect": "Allow",
"Action": [
"secretsmanager:GetResourcePolicy",
"secretsmanager:GetSecretValue",
"secretsmanager:DescribeSecret",
"secretsmanager:ListSecretVersionIds",
"secretsmanager:CreateSecret"
],
"Resource": "*"
}
]
}
Amazon RDS charges an hourly rate for proxies based on the database instance size, see RDS Proxy pricing
SSL/TLS requirements for Amazon RDS connections
To make secure SSL/TLS connections to an Amazon RDS database instance, your Lambda function must verify the database server's identity using a trusted certificate. Lambda handles these certificates differently depending on your deployment package type:
-
.zip file archives: Lambda's managed runtimes include both Certificate Authority (CA) certificates and the certificates required for connections to Amazon RDS database instances. It might take up to 4 weeks for Amazon RDS certificates for new AWS Regions to be added to the Lambda managed runtimes.
-
Container images: AWS base images include only CA certificates. If your function connects to an Amazon RDS database instance, you must include the appropriate certificates in your container image. In your Dockerfile, download the certificate bundle that corresponds with the AWS Region where you host your database. Example:
RUN curl
https://truststore.pki.rds.amazonaws.com/us-east-1/us-east-1-bundle.pem
-o/us-east-1-bundle.pem
This command downloads the Amazon RDS certificate bundle and saves it at the absolute path /us-east-1-bundle.pem
in your container's root directory. When configuring the database connection in your function code, you must reference this exact path. Example:
The readFileSync
function is required because Node.js database clients need the actual certificate content in memory, not just the path to the certificate file. Without readFileSync
, the client interprets the path string as certificate content, resulting in a "self-signed certificate in certificate chain" error.
Example Node.js connection config for OCI function
import { readFileSync } from 'fs';
// ...
let connectionConfig = {
host: process.env.ProxyHostName,
user: process.env.DBUserName,
password: token,
database: process.env.DBName,
ssl: {
ca: readFileSync('/us-east-1-bundle.pem')
// Load RDS certificate content from file into memory
}
};
Connecting to an Amazon RDS database in a Lambda function
The following code examples shows how to implement a Lambda function that connects to an Amazon RDS database. The function makes a simple database request and returns the result.
Note
These code examples are valid for .zip deployment packages only. If you're deploying your function using a container image, you must specify the Amazon RDS certificate file in your function code, as explained in the preceding section.
- AWS SDK for .NET
-
Note
There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples
repository. Connecting to an Amazon RDS database in a Lambda function using .NET.
using System.Data; using System.Text.Json; using Amazon.Lambda.APIGatewayEvents; using Amazon.Lambda.Core; using MySql.Data.MySqlClient; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace aws_rds; public class InputModel { public string key1 { get; set; } public string key2 { get; set; } } public class Function { /// <summary> // Handles the Lambda function execution for connecting to RDS using IAM authentication. /// </summary> /// <param name="input">The input event data passed to the Lambda function</param> /// <param name="context">The Lambda execution context that provides runtime information</param> /// <returns>A response object containing the execution result</returns> public async Task<APIGatewayProxyResponse> FunctionHandler(APIGatewayProxyRequest request, ILambdaContext context) { // Sample Input: {"body": "{\"key1\":\"20\", \"key2\":\"25\"}"} var input = JsonSerializer.Deserialize<InputModel>(request.Body); /// Obtain authentication token var authToken = RDSAuthTokenGenerator.GenerateAuthToken( Environment.GetEnvironmentVariable("RDS_ENDPOINT"), Convert.ToInt32(Environment.GetEnvironmentVariable("RDS_PORT")), Environment.GetEnvironmentVariable("RDS_USERNAME") ); /// Build the Connection String with the Token string connectionString = $"Server={Environment.GetEnvironmentVariable("RDS_ENDPOINT")};" + $"Port={Environment.GetEnvironmentVariable("RDS_PORT")};" + $"Uid={Environment.GetEnvironmentVariable("RDS_USERNAME")};" + $"Pwd={authToken};"; try { await using var connection = new MySqlConnection(connectionString); await connection.OpenAsync(); const string sql = "SELECT @param1 + @param2 AS Sum"; await using var command = new MySqlCommand(sql, connection); command.Parameters.AddWithValue("@param1", int.Parse(input.key1 ?? "0")); command.Parameters.AddWithValue("@param2", int.Parse(input.key2 ?? "0")); await using var reader = await command.ExecuteReaderAsync(); if (await reader.ReadAsync()) { int result = reader.GetInt32("Sum"); //Sample Response: {"statusCode":200,"body":"{\"message\":\"The sum is: 45\"}","isBase64Encoded":false} return new APIGatewayProxyResponse { StatusCode = 200, Body = JsonSerializer.Serialize(new { message = $"The sum is: {result}" }) }; } } catch (Exception ex) { Console.WriteLine($"Error: {ex.Message}"); } return new APIGatewayProxyResponse { StatusCode = 500, Body = JsonSerializer.Serialize(new { error = "Internal server error" }) }; } }
Processing event notifications from Amazon RDS
You can use Lambda to process event notifications from an Amazon RDS database. Amazon RDS sends notifications to an Amazon Simple Notification Service (Amazon SNS) topic, which you can configure to invoke a Lambda function. Amazon SNS wraps the message from Amazon RDS in its own event document and sends it to your function.
For more information about configuring an Amazon RDS database to send notifications, see Using Amazon RDS event notifications.
Example Amazon RDS message in an Amazon SNS event
{ "Records": [ { "EventVersion": "1.0", "EventSubscriptionArn": "arn:aws:sns:us-east-2:123456789012:rds-lambda:21be56ed-a058-49f5-8c98-aedd2564c486", "EventSource": "aws:sns", "Sns": { "SignatureVersion": "1", "Timestamp": "2023-01-02T12:45:07.000Z", "Signature": "tcc6faL2yUC6dgZdmrwh1Y4cGa/ebXEkAi6RibDsvpi+tE/1+82j...65r==", "SigningCertUrl": "https://sns.us-east-2.amazonaws.com/SimpleNotificationService-ac565b8b1a6c5d002d285f9598aa1d9b.pem", "MessageId": "95df01b4-ee98-5cb9-9903-4c221d41eb5e", "Message":
"{\"Event Source\":\"db-instance\",\"Event Time\":\"2023-01-02 12:45:06.000\",\"Identifier Link\":\"https://console.aws.amazon.com/rds/home?region=eu-west-1#dbinstance:id=dbinstanceid\",\"Source ID\":\"dbinstanceid\",\"Event ID\":\"http://docs.amazonwebservices.com/AmazonRDS/latest/UserGuide/USER_Events.html#RDS-EVENT-0002\",\"Event Message\":\"Finished DB Instance backup\"}",
"MessageAttributes": {}, "Type": "Notification", "UnsubscribeUrl": "https://sns.us-east-2.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-east-2:123456789012:test-lambda:21be56ed-a058-49f5-8c98-aedd2564c486", "TopicArn":"arn:aws:sns:us-east-2:123456789012:sns-lambda", "Subject": "RDS Notification Message" } } ] }
Complete Lambda and Amazon RDS tutorial
-
Using a Lambda function to access an Amazon RDS database – From the Amazon RDS User Guide, learn how to use a Lambda function to write data to an Amazon RDS database through an Amazon RDS Proxy. Your Lambda function will read records from an Amazon SQS queue and write new items to a table in your database whenever a message is added.