MONGODB-AWS authentication support for PyMongo
This library provides MONGODB-AWS authentication support for PyMongo, enabling applications to connect to MongoDB using AWS IAM credentials, temporary AWS IAM credentials, or credentials assigned to EC2 instances or ECS tasks. It is currently at version 1.3.0 and aims to align its Python version support with PyMongo's releases.
Warnings
- breaking Version 1.2.0 dropped support for several older Python versions, specifically Python 2.7, 3.4, 3.5, 3.6, and 3.7. Users on these versions must remain on `pymongo-auth-aws<1.2.0` or upgrade their Python environment.
- gotcha With `pymongo-auth-aws>=1.1.0`, the order of credential lookup for AWS authentication now aligns with `boto3`'s default behavior. This means shared AWS credentials or config files might be prioritized over environment variables if not explicitly overridden, which could alter credential resolution compared to earlier versions.
- gotcha The MONGODB-AWS authentication mechanism requires MongoDB server version 4.4+ and PyMongo driver version 3.11+. Ensure your MongoDB deployment and PyMongo version meet these requirements.
- gotcha When using MONGODB-AWS authentication, you must specify `authSource=$external` in your MongoDB connection URI or as a `MongoClient` option. Failing to do so will result in authentication errors.
Install
-
pip install pymongo-auth-aws -
pip install 'pymongo[aws]'
Imports
- MongoClient
from pymongo import MongoClient
Quickstart
import os
from pymongo import MongoClient
from pymongo.server_api import ServerApi
# Set these environment variables for authentication:
# os.environ['AWS_ACCESS_KEY_ID'] = 'YOUR_AWS_ACCESS_KEY_ID'
# os.environ['AWS_SECRET_ACCESS_KEY'] = 'YOUR_AWS_SECRET_ACCESS_KEY'
# os.environ['AWS_SESSION_TOKEN'] = 'YOUR_AWS_SESSION_TOKEN' # Optional, for temporary credentials
# Replace <YOUR_CLUSTER_URI> with your MongoDB Atlas connection string
# Ensure authMechanism=MONGODB-AWS and authSource=$external are set in the URI
# For example: mongodb+srv://<cluster_name>.mongodb.net/?authMechanism=MONGODB-AWS&authSource=%24external&retryWrites=true&w=majority
ATLAS_URI = os.environ.get("MONGODB_AWS_URI", "mongodb+srv://user:pass@host/db?authMechanism=MONGODB-AWS&authSource=%24external")
client = None
try:
# MongoClient will automatically pick up AWS credentials from environment variables
# or other boto3-supported sources if not provided in the URI.
client = MongoClient(ATLAS_URI, server_api=ServerApi('1'))
client.admin.command('ping')
print("Pinged your deployment. You successfully connected to MongoDB using MONGODB-AWS!")
except Exception as e:
print(f"Connection failed: {e}")
finally:
if client:
client.close()