
Updated November 2026: Rewritten around AWS Lambda (the most common way to talk to Atlas from AWS), refreshed for the current Atlas UI, and fixed the connection string so it actually uses IAM auth. EC2, ECS, EKS and laptop options are further down.
TL;DR: MongoDB Atlas can authenticate database users with AWS IAM instead of passwords. Add an Atlas database user whose username is your Lambda function's execution role ARN, and connect with
authSource=$external&authMechanism=MONGODB-AWS. The MongoDB driver reads the role's temporary credentials that Lambda already provides, so there's no password, secret or access key to store.
MongoDB Atlas AWS IAM authentication lets you use AWS IAM (Identity and Access Management) to connect to MongoDB, which removes the need to manage and store database passwords.
The driver signs the request with temporary AWS credentials that expire on their own. Your secret key is never sent to the Atlas cluster and it's never persisted by the MongoDB driver, which makes it more secure than a username and password.
In this article, we'll set up MongoDB Atlas AWS IAM passwordless authentication and connect to an Atlas cluster from a Node.js Lambda function, then verify it in CloudWatch Logs. After that we'll look at other places you can connect from, including EC2 and your own laptop.
How MongoDB Atlas IAM authentication works
- Your Lambda function runs with an IAM execution role.
- Lambda exposes the role's temporary credentials to your code as
AWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEYandAWS_SESSION_TOKENenvironment variables. - The MongoDB driver uses those credentials to sign an
sts:GetCallerIdentityrequest and sends it to Atlas. - Atlas checks the signed identity against the database user's ARN and lets you in with that user's roles.
No password is stored anywhere.
Step 1: Create the Lambda execution role
Let's get started by setting up the AWS side. Create a role that Lambda can assume and give it basic logging permissions:
aws iam create-role \
--role-name atlas-lambda-role \
--assume-role-policy-document '{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": { "Service": "lambda.amazonaws.com" },
"Action": "sts:AssumeRole"
}]
}'
aws iam attach-role-policy \
--role-name atlas-lambda-role \
--policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
The role doesn't need any IAM policy for Atlas. Atlas only checks who you are, not what you're allowed to do in AWS.
Copy the role ARN, for example arn:aws:iam::123456789012:role/atlas-lambda-role. We'll need it in Atlas.
Note: If your function runs inside a VPC, attach
AWSLambdaVPCAccessExecutionRoleinstead ofAWSLambdaBasicExecutionRole.
Step 2: Create an AWS IAM database user in Atlas
In Atlas, go to Security → Database & Network Access, open the Database Users tab and click Add New Database User.

Choose AWS IAM as the Authentication Method.
Set the AWS IAM Type to IAM Role and paste the Lambda execution role ARN you copied in Step 1.

Assign the database privileges the function needs, for example
readWriteon your database. AvoidatlasAdminfor application users.Click Add User.
Step 3: Allow Lambda through the Atlas IP Access List
Atlas checks its IP Access List on every connection, so your function's outbound IP has to be allowed. A Lambda function that isn't attached to a VPC uses AWS's shared public IPs, which change, so there's no single address to add.
For the purpose of this article, we'll allow access from anywhere. On the IP Access List tab, click Add IP Address and add 0.0.0.0/0. The login is still protected by IAM, so only the role you added in Step 2 can actually authenticate.
For production databases: Don't leave
0.0.0.0/0in place. Attach the function to private subnets in your VPC that route through a NAT Gateway, and allowlist only the NAT Gateway's Elastic IPs. For fully private traffic, use VPC peering or an Atlas PrivateLink endpoint instead.
Step 4: Get the connection string
Go to your cluster in Atlas and click Connect, then choose Drivers.
You'll see a connection string with authMechanism=MONGODB-AWS. It may also include an AWS_SESSION_TOKEN placeholder. In Lambda you can drop it, because the driver reads the session token from the environment for you.
Your connection string should look like this:
mongodb+srv://<your_cluster_host>/?authSource=%24external&authMechanism=MONGODB-AWS
The authSource=%24external part is $external URL-encoded. Without authMechanism=MONGODB-AWS, the driver won't try IAM auth at all.
Step 5: Write the Lambda function
Create a small Node.js project and install the MongoDB driver:
mkdir atlas-iam-lambda && cd atlas-iam-lambda
npm init -y
npm install mongodb
Add index.mjs:
import { MongoClient } from "mongodb";
// Created once per execution environment and reused across invocations
const client = new MongoClient(process.env.MONGODB_URI);
export const handler = async () => {
try {
let start = Date.now();
await client.connect();
console.log(`Connected in ${Date.now() - start}ms`);
const demo = client.db("demo");
start = Date.now();
const ping = await demo.command({ ping: 1 });
console.log(`Ping returned ok=${ping.ok} in ${Date.now() - start}ms`);
const { authInfo } = await demo.command({ connectionStatus: 1 });
console.log("Connected to Atlas as:", JSON.stringify(authInfo.authenticatedUsers));
console.log("Roles:", JSON.stringify(authInfo.authenticatedUserRoles));
return { statusCode: 200, body: "Connected to MongoDB Atlas using AWS IAM" };
} catch (error) {
console.error("Failed to connect to MongoDB Atlas:", error);
throw error;
}
};
Creating the MongoClient outside the handler lets warm invocations reuse the connection instead of opening a new one every time.
Step 6: Deploy and test
Package and deploy the function. Notice the environment variable only holds the cluster host and auth options, no secrets:
zip -r function.zip index.mjs package.json node_modules
aws lambda create-function \
--function-name mongodb-test \
--runtime nodejs24.x \
--handler index.handler \
--role arn:aws:iam::123456789012:role/atlas-lambda-role \
--zip-file fileb://function.zip \
--timeout 15 \
--environment "Variables={MONGODB_URI=mongodb+srv://<your_cluster_host>/?authSource=%24external&authMechanism=MONGODB-AWS}"
Invoke it and check the logs.
Voila! The logs show the function connected and authenticated as the IAM role, with the user in the $external database.
Connecting from EC2, ECS and EKS
The same approach works on any AWS compute that runs with an IAM role. Create an Atlas user for that role's ARN and use the same connection string. Only the credential source changes:
| Where your code runs | Give it the role via | Driver reads credentials from |
|---|---|---|
| Lambda | Execution role | AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN env vars |
| EC2 | Instance profile | Instance metadata (IMDSv2) |
| ECS / Fargate | Task role | AWS_CONTAINER_CREDENTIALS_RELATIVE_URI |
| EKS | IAM Roles for Service Accounts (IRSA) | AWS_WEB_IDENTITY_TOKEN_FILE + AWS_ROLE_ARN |
On EC2, you can test straight from the instance with mongosh:
mongosh "mongodb+srv://<your_cluster_host>/?authSource=%24external&authMechanism=MONGODB-AWS"
Don't want to manage SSH keys to get onto the instance? See Access EC2 without SSH key.
Connecting from your laptop or outside AWS
From your own machine, the cleanest option is to assume the same role (or another role mapped to an Atlas user) and export the temporary credentials as environment variables. The driver picks them up, so nothing secret lands in your shell history:
# Assume the role with your AWS CLI profile and export temporary credentials
eval "$(aws configure export-credentials --profile atlas-app --format env)"
mongosh "mongodb+srv://<your_cluster_host>/?authSource=%24external&authMechanism=MONGODB-AWS"
If you're using an IAM user (not recommended for apps), add that user's ARN in Atlas and generate short-lived credentials with:
aws sts get-session-token --duration-seconds 900
Then export AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and AWS_SESSION_TOKEN from the output and run the same mongosh command.
Troubleshooting
- Lambda times out before connecting: That's almost always network, not IAM. Check the Atlas IP Access List:
0.0.0.0/0for a Lambda outside a VPC, or your NAT Gateway's Elastic IP for a Lambda inside one. If you use peering or PrivateLink, check that setup instead. Also raise the function timeout from the default 3 seconds; a cold start plus TLS and auth handshake can take longer. - Authentication failed: The ARN in Atlas must match the role exactly. Use the role ARN (
arn:aws:iam::…:role/name), not theassumed-rolesession ARN you might see in logs. - Works locally but not in Lambda: Make sure you didn't set your own
AWS_ACCESS_KEY_IDenvironment variables on the function. Lambda's role credentials should be the only ones present. - Slow auth outside us-east-1: Set
AWS_STS_REGIONAL_ENDPOINTS=regionalso the driver uses the regional STS endpoint.
FAQ
Does MongoDB Atlas support passwordless authentication with AWS IAM?
Yes. Atlas supports the MONGODB-AWS authentication mechanism, which lets database users authenticate with an AWS IAM role or IAM user ARN instead of a password.
How do I connect AWS Lambda to MongoDB Atlas without a password?
Create an Atlas database user with the AWS IAM authentication method and your Lambda execution role ARN. Then connect with authSource=%24external&authMechanism=MONGODB-AWS in the connection string. The driver uses the credentials Lambda already provides.
Do I need an IAM policy to connect to MongoDB Atlas with IAM?
No. Atlas only verifies the caller's identity through a signed sts:GetCallerIdentity request. Access inside the database is controlled by the Atlas database user's roles.
Which IP address do I add to the Atlas IP Access List for Lambda?
Lambda functions outside a VPC don't have a fixed IP, so for testing you can allow 0.0.0.0/0. For production databases, run the function in private subnets behind a NAT Gateway and allowlist only its Elastic IPs, or use VPC peering or PrivateLink.
What is authSource=$external in the connection string?
$external tells MongoDB the user is authenticated by an external system, AWS IAM in this case. In a URI it's written URL-encoded as %24external.
Is IAM authentication more secure than a database password?
Generally yes. Credentials are temporary and rotate automatically, nothing needs to be stored in config or a secrets manager, and you can revoke access by removing the role or the Atlas user.
Wrapping up
Great job! Your Lambda function now connects to MongoDB Atlas with AWS IAM, without a single password in your config. If you're removing long-lived credentials elsewhere too, check out my series on using OpenID Connect to eliminate IAM user credentials in AWS.
Feel free to comment if you have any doubts. Follow me for more cloud and DevOps content.
References
- MongoDB docs: Set up passwordless authentication with AWS IAM
- MongoDB docs: Configure database users
- MongoDB Node.js driver: AWS IAM authentication
- MongoDB YouTube walkthrough
See you in cloud!
Vishnu S.
Comments
Join the discussionVery informative and well-written article.
Nice article 🙌
very helpful🔥
A very relevant and informative post. Thank you.😊






