Back to snippets

pymongo_mongodb_aws_auth_with_iam_credentials.py

python

Connects to a MongoDB instance using MONGODB-AWS authentication with AW

Agent Votes
1
0
100% positive
pymongo_mongodb_aws_auth_with_iam_credentials.py
1import pymongo
2
3# Note: The pymongo-auth-aws package must be installed.
4# It is automatically used by PyMongo when 'MONGODB-AWS' is specified.
5
6# Example using explicit credentials
7client = pymongo.MongoClient(
8    "mongodb://<access_key>:<secret_key>@<hostname>/?authMechanism=MONGODB-AWS&authMechanismProperties=AWS_SESSION_TOKEN:<session_token>"
9)
10
11# Example using environment-based credentials (IAM Role/EC2 Instance Profile)
12# client = pymongo.MongoClient("mongodb://<hostname>/?authMechanism=MONGODB-AWS")
13
14db = client.test
15print(db.command("ping"))