gokublack
gokublack

Reputation: 1460

Cannot connect RDS Database to a Lambda Function (Using serverless framework)

I want to connect my RDS Database table with my lambda function, for this, I have created a lambda function and used knex.js and postgres database in rds, I got the knex object, but I cannot work with any query.

To give some more information about the services,

My serverless function

module.exports.storeTransaction = async (event) => {  
  ...  
  knex('Transactions')
  .select('*')
  .then(response => {
    console.log('response is ');
    console.log(response);
  })
  ...
};

Serverless.yml file

service: <service-name>

provider:
  name: aws
  runtime: nodejs8.10
  stage: dev
  region: us-east-1

package:
  exclude:
    - node_modules/**
plugins:
  - serverless-plugin-include-dependencies

functions:
  storeEmail:
    handler: handler.storeTransaction
    vpc:
      securityGroupIds:
        - <security-group-id-of-rds>
      subnetIds:
        - <subnet-id-of-rds>
        - <subnet-id-of-rds>
        ...
      region:
        - us-east-1a
    events:
      - http:
          path: email/store
          method: post
          cors: true

So can you identify my issue on why I can't connect my rds db with lambda function, and let me know what I did wrong or what is missing.

Upvotes: 0

Views: 986

Answers (1)

Lorenzo Micheli
Lorenzo Micheli

Reputation: 34

I think the problem is that RDS and Lambda are in different regions, which means they are also in different VPCs, as a VPC cannot span across multiple regions. Although you can enable Inter VPC Peering (https://aws.amazon.com/vpc/faqs/#Peering_Connections).

Consider that when you deploy a lambda function in a VPC, it won't have internet access as long as you don't attach a NAT Gateway to that VPC/subnet.

If the RDS is open to the world (and does it really need to be??), you can try to deploy in the same region (without a VPC) and verify if that works.

Upvotes: 1

Related Questions