Access MongoDB via AWS Lambda

Hi!

I’m trying to connect to MongoDB via AWS Lambda.
I cannot find enough documentation to set this up.

This is what I’ve done.

In mongoDB atlas:
in Authorize AWS IAM Role

  1. Add Atlas to the trust relationships of your AWS IAM role
    I am getting Atlas AWS Account ARN and Your unique External ID
  2. Create New Role with the AWS CLI
    I saved the json that pops us as role-trust-policy.json
  3. Then I use the AWS CLI like this:
    aws iam create-role
    –role-name
    –assume-role-policy-document file://role-trust-policy.json
  4. I enter the role ARN

Now what do I use in my lambda function ?

That video ( Using AWS IAM Authentication with MongoDB 4.4 in Atlas to Build Modern Secure Applications - YouTube ) gives some explanations, but not enough unfortunately.

  1. Do i need to use that role-name in the policy of my AWS lambda?
  2. The following lambda code doesn’t work ( fails with time out ). Is the uri correct?
const {MongoClient} = require('mongodb');
const uri = "mongodb+srv://MYCLUSTER/test?retryWrites=true&w=majority&authSource=%24external&authMechanism=MONGODB-AWS";

const client = new MongoClient(uri,{ useUnifiedTopology: true });
module.exports.handler = async (event, context) => {
  async function listDatabases(client){
    databasesList = await client.db().admin().listDatabases();
    console.log("Databases:");
    databasesList.databases.forEach(db => console.log(` - ${db.name}`));
  };
    try {
    await client.connect();
    await  listDatabases(client);
  } catch (e) {
    console.error(e);
  } finally {
    await client.close();
  }
};

Appreciate any help or any links with more practical documentation.

Cheers! Fred

Hi @Fred_F,

Welcome to MongoDB community.

When you use IAM to connect you still need to create a database user on atlas side associated with the ARN . Later you need to specify its key and secret as user and password for lambda conn string.

Don’t forget you still need to whitelist the Atlas access list , usually via vpc peering lambda vpc to Atlas.

Best
Pavel

Read this guide as well

Thanks Pavel! That was really useful. Fred

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.