用例
我在帐户A中有一个代码提交存储库。我在帐户B中有一个lambda。我需要从我在帐户B中的lambda访问该代码提交存储库。
我做什么
ScriptApp.newTrigger("myFunction")
.timeBased()
.everyWeeks(1)
.create();
的角色,该角色为
CrossAccountRole
并为其分配了信任
帐户B的关系,以便帐户B可以承担角色。我在帐户B中创建了一个codedcommitReadOnlypolicy
策略
ASSUMEROLE
并将其附加到我的用户权限中。
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": [
"sts:AssumeRole",
"sts:GetFederationToken"
],
"Resource": "arn:aws:iam::134952096518:role/CrossAccountRole"
},
{
"Sid": "VisualEditor1",
"Effect": "Allow",
"Action": "sts:GetCallerIdentity",
"Resource": "*"
}
]
}
策略。我确定一切正常。因为当我尝试从AccountB中的控制台切换角色时,我可以看到AccountA中的ASSUMEROLE
。
但是我仍然无法通过我在accountB中的lambda函数连接到AccountA代码提交存储库。
我的lambda函数在accountB中看起来像这样
codecommit Repos
我遇到类似const AWS = require('aws-sdk');
AWS.config.region = 'ap-south-1';
var codecommit = new AWS.CodeCommit({apiVersion: '2015-04-13'});
var params = {
commitId: 'xxx',
repositoryName: 'new'
};
var sts = new AWS.STS();
var sts_params = {
RoleArn: "arn:aws:iam::AccountA:role/CrossAccountRole",
RoleSessionName: "ThisCanBeAnyName"
};
exports.handler = async (event) => {
// TODO implement
try {
const creds = await sts.assumeRole(sts_params).promise();
console.log(creds);
AWS.config.update({
accessKeyId: creds.Credentials.AccessKeyId,
secretAccessKey: creds.Credentials.SecretAccessKey,
sessionToken: creds.Credentials.SessionToken
});
const response = await codecommit.getCommit(params).promise();
const email = response.commit.committer.email;
console.log(response);
} catch (err) {
console.log(err.message);
throw err;
}
};
的错误。由于它是在帐户B中进行搜索,因此出现了这种错误。
感谢任何帮助 谢谢
答案 0 :(得分:0)
对于IAM角色,一切都很好。需要在我的lambda代码中进行一些更改。在我的lambda代码中,我需要将temporary credentials
传递给codecommit
服务,而我在上面的代码中没有这样做。所以,这是工作示例
const AWS = require('aws-sdk');
AWS.config.region = 'ap-south-1';
var params = {
commitId: 'abc',
repositoryName: 'new'
};
var sts = new AWS.STS();
var sts_params = {
RoleArn: "arn:aws:iam::xx:role/CrossAccountRole",
RoleSessionName: "crossaccountRole"
};
exports.handler = async (event) => {
// TODO implement
try {
const creds = await sts.assumeRole(sts_params).promise();
const accessparams2 = {
accessKeyId: creds.Credentials.AccessKeyId,
secretAccessKey: creds.Credentials.SecretAccessKey,
sessionToken: creds.Credentials.SessionToken,
};
const codecommit = await new AWS.CodeCommit(accessparams2);
const response = await codecommit.getCommit(params).promise();
return response;
} catch (err) {
console.log(err.message);
throw err;
}
};
希望对其他人有帮助