Amazon DocumentDB users and applications can use IAM users and roles to authenticate into an Amazon DocumentDB cluster. Amazon DocumentDB IAM authentication is a password-less authentication method in which user passwords are not stored in the Amazon DocumentDB cluster. Also, client applications do not send the password secrets to the Amazon DocumentDB cluster. Instead, client connections are authenticated by AWS STS using temporary security tokens.
In the sample code, we attach an IAM Role to an EC2 instance and run a Python code that authenticates connections to an Amazon DocumentDB cluster using the IAM Role instead of a username-password mechanism.

Create resources with the template file iam_role_sample_cf.yaml using instructions in Selecting a stack template. The AMI used in this templates works in us-east-1 , please change the ami( Amazon Linux 2023) if using in other regions
Replace the following parameters in the stack details screen.

The template will create the resources needed for running this sample including the following:
- An Amazon EC2 Instance with an IAM Role attached to it
- An Amazon DocumentDB cluster with one db.r6g.large instance.
- A security group that enables you to connect to your Amazon DocumentDB cluster from your Amazon EC2 instance.
Once CloudFomation has created all the resources, check the Outputs tab of the stack and note down all the key-value pairs.

SSH into your EC2 instance using the following command:
ssh -i <<KeyPairName_Parameter>>.pem ec2-user@<<InstancePublicIp_Output>>
- Install the mongo shell using the instructions in Install the mongo shell.
- Install required python libraries for Amazon DocumentDB IAM authentication
sudo yum install pip
pip install 'pymongo[aws]'
Download the code sample project from Github
git clone https://github.com/aws-samples/amazon-documentdb-samples.git
Change directory
cd amazon-documentdb-samples/samples/iam_role_sample_code
Get the certificate file needed for TLS communication with Amazon DocumentDB.
wget https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem
Log into mongoshell using the admin user.
mongosh <<DocDBEndpoint_Output>>:27017 --tls --tlsCAFile global-bundle.pem --retryWrites=false --username labuser --password <<DocDBPassword_Parameter>>
Create user in Amazon DocumentDB to link the IAM role attached to the EC2 instance which can found in the InstanceRole Output variable. Once this command is executed, any AWS entity, that assumes the role identified by InstanceRole Output variable,permissions execute read and write operations on the database allowed_db in this cluster.
use $external;
db.createUser(
{
user: "<<InstanceRole_Output>>",
mechanisms: ["MONGODB-AWS"],
roles: [ { role: "readWrite", db: "allowed_db" } ]
}
);
Execute the show users command in mongoshell and confirm that the IAM Role has been linked to a user.
Execute the Python script test_iam_role_docdb.py.
python test_iam_role_docdb.py --docdb-uri 'mongodb://<<DocDBEndpoint_Output>>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false&authSource=%24external&authMechanism=MONGODB-AWS'
This script connects to the Amazon DocumentDB cluster with the IAM Role assumed by the EC2 instance we are running it from. To authenticate using IAM Role, we use the follwing Amazon DocumentDB URI parameters - authSource as $external and authMechanism as MONGODB-AWS. Note that we do not explicitly provide any username-password in the Amazon DocumentDB URI.
After the script completes, check the output.
The script inserts a document and then reads a document from two databases in the cluster - allowed_db and other_db. The operations in allowed_db are successful, and those in other_db fail with authorization errors, because we have granted this IAM Role access to database allowed_db alone - roles: [ { role: "readWrite", db: "allowed_db" } ].
Delete the CloudFormation stack to delete all resources created in this sample.


