Using the AWS SDK for JavaScript, I want to use a default profile that assumes the a role. This works perfectly with the AWS CLI. Using node.js with the SDK does not assume the role, but only uses credentials to the AWS account that the access key belongs to. I've found this documentation but it does not deal with assuming a role: http://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/loading-node-credentials-shared.html
Any tips?
This is my config file:
[default]
role_arn = arn:aws:iam::123456789:role/Developer
source_profile = default
output = json
region = us-east-1
The CLI and SDK work differently, in that you must explicitly assume the role when using the SDK. The SDK doesn't automatically assume the role from the config as the CLI does.
After the role is assumed, the AWS.config must be updated with the new credentials.
This works for me:
Found the correct way to do it! Check out this PR: https://github.com/aws/aws-sdk-js/pull/1391
Just had to add
AWS_SDK_LOAD_CONFIG="true"
to the environment variable along withAWS_PROFILE="assume-role-profile"
So it doesn’t require any code update
The right way to use multiple cross account roles in the code:
Get the credentials for the cross account role with sts and use those credentials every time you need to get a service authenticated with that specific cross account role.
Example:
Create a function to get the cross account credentials like:
And then you can use it without problems like:
Benefits:
The wrong way:
DO NOT USE
AWS.config.update
to override the global credentialsAWS.config.credentials
!!!Override the global credentials is a bad practice!! This is same situation as @Brant's approved solution here but it is no good solution! Here is why:
Issues:
AWS.config.credentials
directly or byAWS.config.update
, will override current credentials.AWS.config.credentials
and update it again to restore it. It is hard to control when you use each account, it is hard to trace execution context, and easy to mess up by targeting the wrong account.Again, DO NOT USE
AWS.config.update
to override the global credentialsAWS.config.credentials
!!!If you need to run the code entirely in another account:
If you need to execute your code entirely for another account without switching between credentials. You can follow the advice from @Kanak Singhal and store the role_arn in the config file and add
AWS_SDK_LOAD_CONFIG="true"
to the environment variable along withAWS_PROFILE="assume-role-profile"
.