如何通过IAM Policy阻止DynamoDB UpdateItem操作创建新记录?
Absolutely! You can restrict DynamoDB's UpdateItem operation to only modify existing records (and block new item creation via this action) using an IAM Policy with DynamoDB's built-in condition keys. Here's a practical breakdown of how to implement this:
Core Idea
By default, UpdateItem creates a new item if the specified partition key doesn't exist. We can fix this by enforcing that every UpdateItem request includes a condition expression verifying the item already exists—and we can lock this requirement into an IAM Policy so users can't bypass it.
Example IAM Policy
This policy lets users view and edit existing records, but blocks UpdateItem from creating new items:
{ "Version": "2012-10-17", "Statement": [ // Allow viewing any existing record (adjust if you need per-user UUID restrictions) { "Effect": "Allow", "Action": "dynamodb:GetItem", "Resource": "arn:aws:dynamodb:YOUR_REGION:YOUR_ACCOUNT_ID:table/YOUR_TABLE_NAME" }, // Allow updating only existing records { "Effect": "Allow", "Action": "dynamodb:UpdateItem", "Resource": "arn:aws:dynamodb:YOUR_REGION:YOUR_ACCOUNT_ID:table/YOUR_TABLE_NAME", "Condition": { "StringEquals": { // Replace "id" with your actual partition key name (e.g., "uuid") "dynamodb:ConditionExpression": "attribute_exists(id)" } } } ] }
Breakdown of the Policy
GetItemAccess: Unrestricted access to view any item in the table. If you need to limit users to specific UUIDs (like those tied to their Cognito identity), add adynamodb:LeadingKeyscondition here, e.g.,"dynamodb:LeadingKeys": ["${cognito-identity.amazonaws.com:sub}"].UpdateItemRestriction: The policy only allowsUpdateItemrequests that include the conditionattribute_exists(id). If a user tries to update a non-existent UUID, DynamoDB rejects the request immediately—and the IAM policy ensures they can't send anUpdateItemcall without this check.
Critical Notes
- Update Placeholders: Swap out
YOUR_REGION,YOUR_ACCOUNT_ID,YOUR_TABLE_NAME, andidwith your actual values. - Frontend Alignment: Your browser app must include the
ConditionExpressionin everyUpdateItemcall. The IAM policy will block any request that omits this, so users can't work around the restriction. - Block
PutItem: Make sure you don't grant usersdynamodb:PutItemaccess (this policy doesn't include it), as that would let them create new items directly.
This setup works seamlessly for browser-direct DynamoDB access (using Amazon Cognito to issue temporary, policy-limited credentials) and stops users from creating new records via the "edit" flow for non-existent UUIDs.
内容的提问来源于stack exchange,提问作者Jesse Barnum

