Issue
I’m trying to connect to atlas cluster from an ec2, but either if I try by code (nodejs) or by cli, I get this error:
MongoError: Could not find user "arn:aws:sts::030800513199:assumed-role/designspecs-staging-design-Api-1U4X5W-InstanceRole-1TTX7XR8B1D7N/*" for db "$external"
It is the right role, the problem is that the registered arn on atlas is the one of the role: arn:aws:iam::030800513199:role/designspecs-staging-design-Api-1U4X5W-InstanceRole-1TTX7XR8B1D7N
And I cannot register the STS one because atlas says it is an invalid arn.
This is the instance role which mongodb should retrieve. If I put in a .env file the keys of a iam user and I make that user a database user for Atlas it works (because the retrieved arn is correct).
Am I missing something? How can I connect the EC2 to atlas without using passwords?
For completeness I should say that I am not assuming any role explicitly, this is the connection code:
const remoteDb = `${MONGO_DATABASE_HOST}/${MONGO_DATABASE_NAME}?authSource=%24external&authMechanism=MONGODB-AWS&retryWrites=true&w=majority`;
const localDb = `mongodb://${MONGO_DATABASE_USERNAME}:${MONGO_DATABASE_PASSWORD}@${MONGO_DATABASE_HOST}:27017/${MONGO_INITDB_DATABASE}`;
const mongoURL = process.env.END !== 'dev' ? remoteDb : localDb;
const connect = () =>
mongoose
.connect(mongoURL, config)
.then(() => {
console.log('[MongoDB] CONNECTED!');
})
.catch(err => {
console.error(err);
console.error(`[MongoDB] ERRROR: NON CONNECTED! -> ${mongoURL}`);
});
connect();
module.exports = mongoose.connection;
Where MONGO_DATABASE_HOST is the srv connection string when I am on remote. All the infrastructure is built with AWS Cloudformation, the role is associated to the instance trough the AWS::IAM::InstanceProfile.
Solution
I found that it was a problem given by the atals user scope. The user used to exist, the problem was that he didn't have the right to see the specific cluster I wanted to connect to. This mistake was given by the fact that I used the aws quickstart template to deploy mongodb, which limits the scope of the user to some resources, removing that part now it works.
Answered By - Emanuele Caruso Answer Checked By - Clifford M. (WPSolving Volunteer)