using profile that assume role in aws-sdk (AWS Jav

2020-02-02 12:31发布

问题:

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

回答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:

var AWS = require('aws-sdk');
AWS.config.region = 'us-east-1';

var sts = new AWS.STS();
sts.assumeRole({
  RoleArn: 'arn:aws:iam::123456789:role/Developer',
  RoleSessionName: 'awssdk'
}, function(err, data) {
  if (err) { // an error occurred
    console.log('Cannot assume role');
    console.log(err, err.stack);
  } else { // successful response
    AWS.config.update({
      accessKeyId: data.Credentials.AccessKeyId,
      secretAccessKey: data.Credentials.SecretAccessKey,
      sessionToken: data.Credentials.SessionToken
    });
  }
});


回答2:

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 with AWS_PROFILE="assume-role-profile"

So it doesn’t require any code update