在代码中使用多个跨账户角色的正确方法:
使用 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.credentials
直接或通过更新 globalAWS.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"
.