Connect Mongodb Altas Using Python

Today we will write a python code in lambda which will connect with our mongodb Atlas and list all databases.

Step 1: Install Dependencies packages in Lambda Layers.

1Package:
21: pymongo
32: dnspython

Note: To learn how to add python packages in lambda layers. Use the this [link] (https://www.cloudkaramchari.com/blog/upload-python-package-in-lambda-layer/)

Step 2: Open IAM service console.

Step 3: Create IAM policy for an IAM Role.

  • Copy the below policy and paste it in your IAM policy.
 1{
 2    "Version": "2012-10-17",
 3    "Statement": [
 4        {
 5            "Sid": "VisualEditor0",
 6            "Effect": "Allow",
 7            "Action": "logs:*",
 8            "Resource": "arn:aws:logs:*:*:log-group:*:log-stream:*"
 9        },
10        {
11            "Sid": "VisualEditor1",
12            "Effect": "Allow",
13            "Action": [
14                "logs:*"
15            ],
16            "Resource": [
17                "arn:aws:logs:*:*:log-group:*"
18            ]
19        }
20    ]
21}

Note: To know how to create a custom IAM policy , Please follow this link

Step 4: Create IAM Role and Attach the above IAM policy.

Note: To know how to create IAM Role, Please follow the this link

Step 5: Open Lambda console.

Step 6: Create Lambda Function.

To create an Lambda Function, Go to Lambda service from AWS console and create a new Function.

Lambda Console

  • Add Lambda Function name. (You can write any name).
  • In Runtime info, Choose "Python 3.9".
  • In permission, Choose "Use an existing Role" in Execution Role
  • In Existing Role, choose the IAM role which you have create above for this Lambda Function.
  • Click on "Create Function".
  • Go to "Function Code" and Paste the below Python code in it.
 1import json
 2from pymongo import MongoClient
 3import pymongo
 4    
 5def lambda_handler(event, context):
 6
 7    client = pymongo.MongoClient("mongodb+srv://<user-name>:<user-password>@<connection-string>/?retryWrites=true&readPreference=secondary")  
 8    for name in client.list_database_names():  
 9        print(name)
10

Step 7: Now Select your dependencies from layer into your function.

Step 8: Click on Layers

Lambda COnsole Function

Step 9: Click on "Add a Layer". Add your package and version.

Layer Function

Step 10: Increase the default timeout from the configuration.

Step 11: Save the Lambda Function and Test the same.

I :heart: AWS! :smile: Enjoy