MONGODB-AWS authentication support for PyMongo

1.3.0 · active · verified Sat Apr 11

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

Install

Imports

Quickstart

This example demonstrates connecting to MongoDB Atlas using the `MONGODB-AWS` authentication mechanism. It assumes `pymongo-auth-aws` is installed and AWS credentials (access key ID, secret access key, and optionally a session token) are configured in the environment variables (e.g., `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`). The `authMechanism=MONGODB-AWS` and `authSource=$external` parameters are crucial in the connection URI.

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()

view raw JSON →