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

using profile that assume role in aws-sdk (AWS JavaScript SDK)

使用 JavaScript 的 AWS SDK,我想使用承担 a 角色的默认配置文件。这与 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

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
    });
  }
});

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

只需将 AWS_SDK_LOAD_CONFIG="true"AWS_PROFILE="assume-role-profile"

一起添加到环境变量

因此不需要任何代码更新

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

代码中使用多个跨账户角色的正确方法:

使用 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,
        });
      }
    });
  });
}

然后你就可以毫无问题地使用它了:

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.
}

好处:

  • 不会全局更改凭据,因此您仍然可以针对自己的 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!!!
}

问题:

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

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

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

如果您需要在不切换凭据的情况下完全为另一个帐户执行代码。您可以按照@Kanak Singhal 的建议将 role_arn 存储在配置文件中,并将 AWS_SDK_LOAD_CONFIG="true"AWS_PROFILE="assume-role-profile".

一起添加到环境变量中

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

它会自动刷新凭据并可在多个层中链接

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

我自己在想 运行 扮演角色时发现了这个问题,所以我猜它仍然具有一定的 SEO 功能!