AWS ‐ Secret Manager for Mongodb - FullstackCodingGuy/Developer-Fundamentals GitHub Wiki

✅ Securely Storing MongoDB Credentials in AWS Secrets Manager for Lambda

To securely store and use your MongoDB (DocumentDB) connection credentials in AWS Lambda, follow these steps:


1️⃣ Store MongoDB Credentials in AWS Secrets Manager

  1. Go to AWS Console → Secrets Manager
  2. Click "Store a new secret"
  3. Select "Other type of secret"
  4. Add your MongoDB credentials in Key-Value format:
    {
      "mongodb_uri": "mongodb://your-user:your-password@your-documentdb-cluster:27017/your-database?ssl=true&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false"
    }
    
  5. Click Next, name the secret:
    mongodb/credentials
    
  6. Click Store.

2️⃣ Grant Lambda Access to AWS Secrets Manager

Your Lambda function needs permission to retrieve the MongoDB secret.

Update your IAM Role to include this policy:

{
  "Effect": "Allow",
  "Action": "secretsmanager:GetSecretValue",
  "Resource": "arn:aws:secretsmanager:YOUR_REGION:YOUR_ACCOUNT_ID:secret:mongodb/credentials-*"
}

3️⃣ Update Lambda Code to Fetch MongoDB URI

Install AWS SDK for Secrets Manager

npm install @aws-sdk/client-secrets-manager mongoose

Modify Code to Retrieve MongoDB URI

const { SecretsManagerClient, GetSecretValueCommand } = require("@aws-sdk/client-secrets-manager");
const mongoose = require("mongoose");

const secretsClient = new SecretsManagerClient({ region: process.env.AWS_REGION || "us-east-1" });

const getMongoDBURI = async () => {
  try {
    const secret = await secretsClient.send(new GetSecretValueCommand({ SecretId: "mongodb/credentials" }));
    const secretValue = JSON.parse(secret.SecretString);
    return secretValue.mongodb_uri;
  } catch (err) {
    console.error("❌ Error fetching MongoDB secret:", err);
    throw err;
  }
};

const connectMongoDB = async () => {
  try {
    const mongoURI = await getMongoDBURI(); // Fetch the URI from Secrets Manager
    await mongoose.connect(mongoURI, {
      useNewUrlParser: true,
      useUnifiedTopology: true
    });
    console.log("✅ Connected to MongoDB using AWS Secrets Manager");
  } catch (err) {
    console.error("❌ MongoDB Connection Error:", err);
  }
};

module.exports = connectMongoDB;

4️⃣ Deploy Lambda with AWS SAM

Update template.yaml to include AWS Region:

Environment:
  Variables:
    AWS_REGION: "us-east-1"

Then build and deploy:

sam build && sam deploy --guided

🚀 Final Steps

✅ Store MongoDB credentials securely in AWS Secrets Manager
IAM Role allows Lambda to fetch secrets
✅ Lambda dynamically retrieves MongoDB URI at runtime
No hardcoded credentials in the code 🎉

Now, restart your Lambda function, and it should securely connect to MongoDB! 🔥