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
- Add Atlas to the trust relationships of your AWS IAM role
I am getting Atlas AWS Account ARN and Your unique External ID - Create New Role with the AWS CLI
I saved the json that pops us as role-trust-policy.json - Then I use the AWS CLI like this:
aws iam create-role
–role-name
–assume-role-policy-document file://role-trust-policy.json - 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.
- Do i need to use that role-name in the policy of my AWS lambda?
- 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