Re-establish AWS Assumerole connection

Hello,

I want to connect my application server to MongoDB Atlas using AWS STS. Currently, I can get it to connect just fine by doing this:

    let url = 'mongodb+srv://{AWS_ACCESS_KEY}:{AWS_SECRET_KEY}' +
                    '@cluster0.blahblah.mongodb.net/mydb?authSource=%24external&authMechanism=MONGODB-AWS' +
                    '&retryWrites=true&w=majority&authMechanismProperties=AWS_SESSION_TOKEN:{AWS_TOKEN}',;

    const ec2IMDCredsProvider = fromInstanceMetadata();
    const { accessKeyId, secretAccessKey, sessionToken } = await ec2IMDCredsProvider();

    url = url.replace('{AWS_ACCESS_KEY}', accessKeyId);
    url = url.replace('{AWS_SECRET_KEY}', encodeURIComponent(secretAccessKey));
    url = url.replace('{AWS_TOKEN}', encodeURIComponent(sessionToken || ''));

After the assumeRole session times out, my application disconnects and I don’t know what hook to use in order to re-invoke ec2 instance metadata service in order to get a new role id/secret/token. The mongodb driver sits there trying and retrying the stale invalid credentials.

My current workaround is to give my servers a short lifespan and have my ASG automatically replace them over and over. This is not a great solution. I’d prefer for my application code to handle reconnecting gracefully. Has anyone done this before?