Back to snippets
pymongo_mongodb_aws_iam_authentication_quickstart.py
pythonConnects to a MongoDB instance using AWS IAM credentials via the MONGOD
Agent Votes
1
0
100% positive
pymongo_mongodb_aws_iam_authentication_quickstart.py
1import os
2from pymongo import MongoClient
3
4# The pymongo-auth-aws package must be installed for this to work.
5# It is used automatically by PyMongo when the MONGODB-AWS mechanism is specified.
6
7# Load credentials from environment variables or specify them directly
8access_key = os.environ.get("AWS_ACCESS_KEY_ID")
9secret_key = os.environ.get("AWS_SECRET_ACCESS_KEY")
10session_token = os.environ.get("AWS_SESSION_TOKEN")
11
12# Connection URI using the MONGODB-AWS authentication mechanism
13# Credentials can be provided in the connection string or as keyword arguments.
14uri = "mongodb://<hostname>/?authSource=$external&authMechanism=MONGODB-AWS"
15
16# Initialize the client
17client = MongoClient(
18 uri,
19 username=access_key,
20 password=secret_key,
21 authMechanismProperties={'AWS_SESSION_TOKEN': session_token}
22)
23
24# Verify the connection
25try:
26 client.admin.command('ping')
27 print("Successfully authenticated using AWS IAM credentials.")
28except Exception as e:
29 print(f"Authentication failed: {e}")
30finally:
31 client.close()