amazon-dynamodb - DynamoDB w/ Serverless,使用 Fn::GetRef 来引用全局二级索引
问题描述
我有一个使用 DynamoDB 表定义的 API/服务。我有几个索引(定义为全局二级索引)来支持几个查询。我设计了带有 GSI 定义的表,并且看起来像正确的查询。但是,在进行查询时出现此异常:
{ AccessDeniedException: User: arn:aws:sts::OBSCURED:assumed-role/chatroom-application-dev-us-east-1-lambdaRole/chatroom-application-dev-getRoomMessages is not authorized to perform: dynamodb:Query on resource: arn:aws:dynamodb:us-east-1:OBSCURED:table/messages-table-dev/index/roomIndex
at Request.extractError (/var/task/node_modules/aws-sdk/lib/protocol/json.js:48:27)
at Request.callListeners (/var/task/node_modules/aws-sdk/lib/sequential_executor.js:105:20)
at Request.emit (/var/task/node_modules/aws-sdk/lib/sequential_executor.js:77:10)
at Request.emit (/var/task/node_modules/aws-sdk/lib/request.js:683:14)
at Request.transition (/var/task/node_modules/aws-sdk/lib/request.js:22:10)
at AcceptorStateMachine.runTo (/var/task/node_modules/aws-sdk/lib/state_machine.js:14:12)
at /var/task/node_modules/aws-sdk/lib/state_machine.js:26:10
at Request.<anonymous> (/var/task/node_modules/aws-sdk/lib/request.js:38:9)
at Request.<anonymous> (/var/task/node_modules/aws-sdk/lib/request.js:685:12)
at Request.callListeners (/var/task/node_modules/aws-sdk/lib/sequential_executor.js:115:18)
message: 'User: arn:aws:sts::OBSCURED:assumed-role/chatroom-application-dev-us-east-1-lambdaRole/chatroom-application-dev-getRoomMessages is not authorized to perform: dynamodb:Query on resource: arn:aws:dynamodb:us-east-1:OBSCURED:table/messages-table-dev/index/roomIndex',
code: 'AccessDeniedException',
time: 2018-06-02T22:05:46.110Z,
requestId: 'OBSCURED',
statusCode: 400,
retryable: false,
retryDelay: 30.704899664776054 }
在异常的顶部,它显示了我的 getRoomMessages 方法is not authorized to perform: dynamodb:Query on resource:
的 ARN,并显示了全局二级索引的 ARN。
似乎很清楚,我需要定义策略来授予访问全局二级索引的权限。但目前还不清楚如何。我看到其他有关 DynamoDB 的 StackOverflow 问题抱怨文档碎片化以及找到任何东西有多困难。我不得不同意。“碎片化”这个词说得太轻了。
我正在使用无服务器框架。该provider
部分显示了此策略/角色定义:
provider:
name: aws
runtime: nodejs8.10
stage: dev
region: us-east-1
iamRoleStatements:
- Effect: Allow
Action:
- dynamodb:Query
- dynamodb:Scan
- dynamodb:GetItem
- dynamodb:PutItem
- dynamodb:UpdateItem
- dynamodb:DeleteItem
Resource:
- { "Fn::GetAtt": ["MessagesDynamoDBTable", "Arn" ] }
- { "Fn::GetAtt": ["#roomIndex", "Arn" ] }
- { "Fn::GetAtt": ["#userIndex", "Arn" ] }
environment:
MESSAGES_TABLE: ${self:custom.tableName}
在该Resource
部分中,我相信我应该列出声明了权限的资源。第一个引用整个表格。我刚刚添加的最后两个,并引用了索引。
编辑:当我运行时serverless deploy
打印以下消息:
The CloudFormation template is invalid: Template error: instance of Fn::GetAtt references undefined resource #roomIndex
我对此尝试了几种变体,只是为了得到相同的错误。这归结为 -我如何serverless.yml
使用 Cloudfront 语法获取索引的 ARN。ARN 确实存在,因为它显示在异常中。
DynamoDB 表定义:
resources:
Resources:
MessagesDynamoDBTable:
Type: AWS::DynamoDB::Table
Properties:
AttributeDefinitions:
- AttributeName: messageId
AttributeType: S
- AttributeName: room
AttributeType: S
- AttributeName: userId
AttributeType: S
KeySchema:
- AttributeName: messageId
KeyType: HASH
GlobalSecondaryIndexes:
- IndexName: roomIndex
KeySchema:
- AttributeName: room
KeyType: HASH
Projection:
ProjectionType: ALL
ProvisionedThroughput:
ReadCapacityUnits: 1
WriteCapacityUnits: 1
- IndexName: userIndex
KeySchema:
- AttributeName: userId
KeyType: HASH
Projection:
ProjectionType: ALL
ProvisionedThroughput:
ReadCapacityUnits: 1
WriteCapacityUnits: 1
ProvisionedThroughput:
ReadCapacityUnits: 1
WriteCapacityUnits: 1
TableName: ${self:custom.tableName}
正在使用的查询对应于上述异常:
{
"TableName": "messages-table-dev",
"IndexName": "roomIndex",
"KeyConditionExpression": "#roomIndex = :room",
"ExpressionAttributeNames": {
"#roomIndex": "room"
},
"ExpressionAttributeValues": {
":room": {
"S": "everyone"
}
}
}
以及生成查询的 Lambda 函数代码片段:
app.get('/messages/room/:room', (req, res) => {
const params = {
TableName: MESSAGES_TABLE,
IndexName: "roomIndex",
KeyConditionExpression: '#roomIndex = :room',
ExpressionAttributeNames: { '#roomIndex': 'room' },
ExpressionAttributeValues: {
":room": { S: `${req.params.room}` }
},
};
console.log(`QUERY ROOM ${JSON.stringify(params)}`);
dynamoDb.query(params, (error, result) => {
if (error) {
console.log(error);
res.status(400).json({ error: 'Could not get messages' });
} else {
res.json(result.Items);
}
});
});
解决方案
我找到了比 jake.lang 发布的更好的答案。编辑:我没有看到他提出以下建议的第二条评论。
正如他所指出的,他的做法是不正确的,因为 ARN 可以出于正当理由而更改。但是,出现了解决方案,因为全局二级索引的 ARN 是将“/INDEXNAME”附加到表的 ARN。这意味着政策声明可以是:
iamRoleStatements:
- Effect: Allow
Action:
- dynamodb:Query
- dynamodb:Scan
- dynamodb:GetItem
- dynamodb:PutItem
- dynamodb:UpdateItem
- dynamodb:DeleteItem
Resource:
- { "Fn::GetAtt": ["MessagesDynamoDBTable", "Arn" ] }
- { "Fn::Join": [ "/", [
{ "Fn::GetAtt": ["MessagesDynamoDBTable", "Arn" ] }, "index", "roomIndex"
]]}
- { "Fn::Join": [ "/", [
{ "Fn::GetAtt": ["MessagesDynamoDBTable", "Arn" ] }, "index", "userIndex"
]]}
“Fn::Join”位来自 CloudFormation,是一个“加入”操作。它需要一个字符串数组,使用第一个参数将它们连接起来。因此,计算本政策声明中所需的 ARN 是一种相当复杂且过于复杂的方法。
推荐阅读
- c# - 无法对 mvc 中的空引用执行运行时绑定
- javascript - 将数据从一个 js 传递到另一个 js
- c++ - 使用就地 lambda 进行复杂的初始化,尤其是 consts
- css - 无法从:悬停元素中删除下划线,并且在 chrome 检查器中看不到文本装饰:下划线
- typo3 - TYPO3 queryBuilder:如何在 where() 子句中使用 BINARY?
- semantic-ui - 如何在语义ui中为输入添加多个图标
- haskell - 如何修复我的 Haskell 条件语句?
- angular - 角度路由与延迟加载模块的预期不同。手动输入 url 但从导航菜单总是重定向到默认路由
- bigdata - Apache Ignite:数据区域内存不足 [name=Default_Region,initSize=256.0 MiB,maxSize=68.0 GiB,persistenceEnabled=false]
- javascript - 访问 json React Native 中的嵌套值