代码中使用多个跨账户角色的正确方法:
使用 sts 获取跨帐户角色的凭据,并在每次需要使用该特定跨帐户角色对服务进行身份验证时使用这些凭据。
Example:
创建一个函数来获取跨帐户凭据,例如:
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!!!
}
Issues:
- 更新全球
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"
.