假设我们有两个AWS帐户,帐户名称为 devo 和 prod 。因此,在 prod 上,我有一个dynamoDB
表,我想使用lambda
函数访问该表,该函数中存在于 devo 中。现在,我所做的是在 prod 中创建一个策略,该策略可以完全访问dynamoDB
,并将该策略附加到Prod帐户中的role
,该策略作为信任帐户 devo 。在> devo 我创建了一个角色,该角色具有 lambda >的完整访问权限,并附加了一个内联策略,该策略允许假设 prod 的role
。另外,我能够使用AWS控制台从 devo 帐户中的pabil wife从dynamoDB
获取数据。
以下是lambda
功能:
const AWS = require('aws-sdk');
var cred = new AWS.CredentialProviderChain();
var sts = new AWS.STS({credentials: cred, region: 'us-east-1'});
var crd2 ;
var params = {
RoleArn: "arn:aws:iam::123456789012:role/crossAccount",
RoleSessionName: "atul"
};
sts.assumeRole(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else {
crd2 = data; // successful response
console.log("Role assured");
}
});
const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10', credentials: crd2, region: 'eu-west-1', endpoint: 'https://dynamodb.eu-west-1.amazonaws.com'});
exports.handler = (event, context, callback) => {
console.log(crd2);
console.log("**** " + JSON.stringify(dynamodb));
dynamodb.getItem({
TableName: "Testing",
Key: {
"Id": {
S: "1121091591"
}
}
}, function(err, data) {
if (err) {
console.log(err, err.stack);
callback(null, {
statusCode: '500',
body: err
});
} else {
console.log(data);
callback(null, {
statusCode: '200',
body: 'Hello '
});
}
})
};
这是我遇到的错误:
{
"message": "Requested resource not found",
"code": "ResourceNotFoundException",
"time": "2019-03-05T17:54:35.920Z",
"requestId": "LAN0EI8B2I6I4CVI4OUH01MI3JVV4KQNSO5AEMVJF66Q9ASUAAJG",
"statusCode": 400,
"retryable": false,
"retryDelay": 11.869537309323096
}
谢谢
我认为您的代码正在构建DynamoDB客户端,因为JavaScript的AWS SDK是异步的。我认为您可以通过添加长睡眠命令来查看它是否开始工作来测试这一点。确定是否是问题后,此页面来自AWS,将帮助您更改代码以正确工作
https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/calling-services-services-aservices-asernchronely.html
lambda不假定提供给lambda的所有假设角色访问。一个人需要特别要求lambda担任特定角色。
这是一个简单的Java实现
final AWSSecurityTokenService stsClient =
AWSSecurityTokenServiceClientBuilder.standard()
.withRegion(REGION)
.withCredentials(DefaultAWSCredentialsProviderChain.getInstance())
.build();
final AssumeRoleResult assumeRoleResult = stsClient.assumeRole(
new AssumeRoleRequest()
.withRoleArn("<DynamoDBRoleArn>")
.withRoleSessionName("DummyLambdaRoleSessionName"));
final BasicSessionCredentials sessionCredentials = new BasicSessionCredentials(
assumeRoleResult.getCredentials().getAccessKeyId(),
assumeRoleResult.getCredentials().getSecretAccessKey(),
assumeRoleResult.getCredentials().getSessionToken());
return AmazonDynamoDBClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(sessionCredentials))
.withRegion(REGION)
.build();