gpt4 book ai didi

node.js - 寻找更新 AWS 凭证的更好方法

转载 作者:行者123 更新时间:2023-12-05 03:02:14 25 4
gpt4 key购买 nike

我正在使用 sts:assumeRole 连接到不同账户的 s3 存储桶。现在,我运行的作业需要几天的时间,并且在凭证到期的过程中,我需要一种方法来更新它们。

我编写了以下代码来处理临时凭证的过期

此代码在我的 downloadFile() 中:

return new Promise((resolve, reject) => {
function responseCallback(error, data) {
if (error) {
const errorMessage = `Fail to download file from s3://${config().s3.bucket}/${path}: ${error};`;
reject(error);
} else {
Logger.info(`Successfully download file from s3://${config().s3.bucket}/${path}`);
resolve(data.Body);
}
}
const fn = this.s3Client.getObject({
Bucket: config().s3.bucket,
Key: path
}, (error, data) => this.handleTokenExpiry(error, data, fn, responseCallback));
});

这是 handleTokenExpiry()

handleTokenExpiry(error, data, fn, callback) {
if (!error || error.code !== "ExpiredToken") return callback(error, data);

Logger.info("Token expired, creating new token");
this.s3Client = null; // null so that init() doesn't return existing s3Client
return this.init().then(fn);
}

这里的init()是使用sts:assumeRole设置this.s3Client的方法然后是 new AWS.S3()

这工作正常,但我不确定这是否是一种干净的方法。奇怪的是,当我在本地测试它时,当 token 过期时调用 responseCallback() 需要将近 两分钟。虽然当 token 处于事件状态时 responseCallback() 会立即执行。

最佳答案

对于运行时间少于 12 小时的任务,这里是解决方案。

使用AssumeRole时,您可以指定DurationSeconds参数来指定STS返回的临时凭证的持续时间。这是最少 15 分钟,最多 12 小时。

您承担的角色也需要修改以授权最长持续时间。参见 https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html#id_roles_use_view-role-max-session

在您的情况下,工作运行了几天。我建议重构应用程序以小批量运行,每次运行几个小时。

另一种选择是主动应对 token 过期。如果您的代码知道 token 持续时间和获取 token 的时间,我建议在调用使用 token 的方法(例如 S3 的 getObject)之前先调用一个方法。该方法检查 token 是否即将过期并主动刷新它们。伪代码就像

function refreshToken() {
return new Promise( (resolve, reject) => {
// XX depends how long is your S3 getObject call
if (token_acquisition_time + token_duration <= now() + xx minutes) {
// refresh token
sts.assumeRole(...).promise().then(resolve());
} else {
resolve();
}
});
}

...

refreshToken.then(s3.getObject(...));

关于node.js - 寻找更新 AWS 凭证的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55099370/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com