AWS SAM is a great resource for building serverless projects and deploying them to AWS. We use it a lot at Enteka (the company that builds and maintains Protypo). When building an API you will quite typically want to connect to a database. With AWS we can use RDS to deploy and manage a database for us. For security RDS will place the database instance within a VPC which means by default the database is not publicly accessible (which is a good thing) and that other resources that will want to access the database such as a Lambda function will either need to be deployed in the same VPC or will need to connect to the VPC via linking.
We won’t be exploring the second option in this tutorial. Instead, I’ll be showing you how to deploy your Lambda functions to the same VPC that your database instance lives in using AWS SAM so that Lambda can connect to the database.
I’m going to skip the part of deploying the RDS instance to the VPC as that is another tutorial in itself and setting up an AWS SAM project. We will be writing tutorials on both these subjects in the future so make sure you follow us to know when they’re publish. So we’re going to assume that you have an RDS instance up and running inside of a VPC and an AWS project.
Firstly, we need to find the ID of the subnets in the VPC where our RDS instance lives and the security group ID that our RDS instance uses. You can do this by:
sg-
Now we have the security group ID and the subnets we need to open up the template.yaml
file in our AWS SAM project. We’re going to define a new section called VpcConfig
in the Function
section inside of the Globals
section. We’re going to define two child values of VpcConfig
called SecurityGroupIds
and SubnetIds
. Both of these values
take a list of values. Below the SecurityGroupIds
on a new line paste the Security group ID you copied earlier. And then below the SubnetIds
on a new line for each one paste the
subnet IDs copied from earlier. The Globals
section of your SAM template should now look something like this:
Globals:
Function:
Timeout: 5
VpcConfig:
SecurityGroupIds:
- sg-008989453956349
SubnetIds:
- subnet-890890890
- subnet-423784563
- subnet-463278679
That is it! Now when you deploy your serverless API with sam deploy
your Lambda functions will deployed to the same VPC as your RDS instance and will be able to connect to it freely!