使用在aws-sdk中扮演角色的配置文件(AWS JavaScript SDK)

And*_*ard 18 node.js aws-sdk aws-sdk-nodejs

使用AWS SDK for JavaScript,我想使用一个承担角色的默认配置文件.这与AWS CLI完美配合.将node.js与SDK一起使用不承担该角色,而只使用访问密钥所属的AWS账户的凭据.我找到了这个文档,但它没有涉及假设一个角色:http://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/loading-node-credentials-shared.html

有小费吗?

这是我的配置文件:

[default]
role_arn = arn:aws:iam::123456789:role/Developer
source_profile = default
output = json
region = us-east-1
Run Code Online (Sandbox Code Playgroud)

Kan*_*hal 19

找到了正确的方法!看看这个PR:https: //github.com/aws/aws-sdk-js/pull/1391

只需要添加AWS_SDK_LOAD_CONFIG="true"到环境变量AWS_PROFILE="assume-role-profile"

所以它不需要任何代码更新:sweat_smile:

编辑:

这是因为,SDK只加载credentials文件是默认config文件,而不是文件,但由于aws role_arn存储在config文件中,我们也必须启用加载config文件.


Bra*_*ant 18

CLI和SDK的工作方式不同,因为您在使用SDK时必须明确承担该角色.SDK不会像CLI那样自动承担配置中的角色.

假定角色后,必须使用新凭据更新AWS.config.

这对我有用:

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
    });
  }
});
Run Code Online (Sandbox Code Playgroud)

  • 我的猜测是,在您的用例中调用 `AWS.config.update` 不是正确的做法。后续凭据可能无权承担该角色。 (3认同)
  • 这种方法不考虑凭证到期。sdk 支持开箱即用。看看@Kanak Singhal 的回答。 (3认同)
  • 我想知道 AWS 何时开始在其文档中添加此隐藏步骤。 (2认同)

Eri*_*son 6

聚会有点晚了,但现在最简单的方法可能是使用AWS.ChainableTemporaryCredentials

它会自动刷新凭据,并且可以在多个层中链接,或者在此处使用默认凭据

AWS.config.credentials = new AWS.ChainableTemporaryCredentials({
  params: {RoleArn: 'RoleARN', RoleSessionName: 'RoleSessionName'}
});
Run Code Online (Sandbox Code Playgroud)

https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/ChainableTemporaryCredentials.html

当我想以假设的角色运行时,我自己发现了这个问题,所以我猜它仍然有一些 SEO 能力!


Fac*_*tor 5

在代码中使用多个交叉帐户角色的正确方法

使用sts获取交叉帐户角色的凭据,并在每次需要使用该特定交叉帐户角色进行身份验证的服务时使用这些凭据。

例:

创建一个函数来获取交叉帐户凭据,例如:

const AWS = require('aws-sdk');
const sts = new AWS.STS();

const getCrossAccountCredentials = async () => {
  return new Promise((resolve, reject) => {
    const timestamp = (new Date()).getTime();
    const params = {
      RoleArn: 'arn:aws:iam::123456789:role/Developer',
      RoleSessionName: `be-descriptibe-here-${timestamp}`
    };
    sts.assumeRole(params, (err, data) => {
      if (err) reject(err);
      else {
        resolve({
          accessKeyId: data.Credentials.AccessKeyId,
          secretAccessKey: data.Credentials.SecretAccessKey,
          sessionToken: data.Credentials.SessionToken,
        });
      }
    });
  });
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用它而不会出现以下问题:

const main = async () => {
  // Get the Cross account credentials
  const accessparams = await getCrossAccountCredentials();
  // Get the ec2 service for current account
  const ec2 = new AWS.EC2();
  // Get the ec2 service for cross account role
  const ca_ec2 = new AWS.EC2(accessparams);
  // Get the autoscaling service for current account
  const autoscaling = new AWS.AutoScaling();
  // Get the autoscaling service for cross account role
  const ca_autoscaling = new AWS.AutoScaling(accessparams);

  // This will describe instances within the cross account role
  ca_ec2.describeInstances(...) 

  // This will describe instances within the original account
  ec2.describeInstances(...)

  // Here you can access both accounts without issues.
}
Run Code Online (Sandbox Code Playgroud)

优点:

  • 不会在全球范围内更改凭证,因此您仍然可以定位自己的AWS账户,而无需事先备份凭证即可将其还原。
  • 允许您精确控制每时每刻要定位的帐户。
  • 允许处理多个交叉帐户角色和服务。

错误的方式

请勿使用AWS.config.update以覆盖全局凭据AWS.config.credentials

覆盖全局凭据是一个坏习惯!!这与@Brant批准的解决方案相同,但这不是一个好的解决方案!原因如下:

const main = async () => {
  // Get the Cross account credentials
  const accessparams = await getCrossAccountCredentials();

  // Get the ec2 service for current account
  const ec2 = new AWS.EC2();

  // Overwrite the AWS credentials with cross account credentilas
  AWS.config.update(accessparams);

  // Get the ec2 service for cross account role
  const ca_ec2 = new AWS.EC2();

  // This will describe instances within the cross account role
  ca_ec2.describeInstances(...) 

  // This will ALSO describe instances within the cross account role
  ec2.describeInstances(...)

  // WARNING: Here you only will access the cross account role. You may get
  // confused on what you're accessing!!!
}
Run Code Online (Sandbox Code Playgroud)

问题:

  • AWS.config.credentials直接或通过全局更新AWS.config.update,将覆盖当前凭据。
  • 一切都将指向该跨帐户角色,甚至将来您可能不会期望的服务调用。
  • 要切换回第一个帐户,您可能需要临时备份AWS.config.credentials并再次更新以恢复它。很难控制何时使用每个帐户,很难跟踪执行上下文,并且容易因定位错误的帐户而混乱。

同样,请勿使用AWS.config.update覆盖全局凭据AWS.config.credentials

如果您需要完全在另一个帐户中运行代码

如果您需要完全为另一个帐户执行代码,而无需在凭据之间切换。您可以遵循@Kanak Singhal的建议,并将role_arn存储在配置文件中,并与一起添加AWS_SDK_LOAD_CONFIG="true"到环境变量中AWS_PROFILE="assume-role-profile"

  • 这是一个更好的解决方案!谢谢。 (3认同)