I try to build test lambda which going to store data to DynamoDb via http request. My serverless.yml:
service: your-pet-project
frameworkVersion: '3'
provider:
name: aws
runtime: nodejs12.x
region: us-east-1
iamRoleStatements:
- Effect: Allow
Action:
- dynamodb:PutItem
Resource: "arn:aws:dynamodb:${self:provider.region}:*:table/MyTestTable"
functions:
store:
handler: store.storeData
events:
- http:
path: store
method: post
cors: true
resources:
Resources:
MyTestTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: MyTestTable
AttributeDefinitions:
- AttributeName: id
AttributeType: S
KeySchema:
- AttributeName: id
KeyType: HASH
ProvisionedThroughput:
ReadCapacityUnits: 1
WriteCapacityUnits: 1
All attempt to call store endpoint finish:
ERROR AccessDeniedException: User: arn:aws:sts::293839420735:assumed-role/your-pet-project-dev-us-east-1-lambdaRole/your-pet-project-dev-store is not authorized to perform: dynamodb:PutItem on resource: arn:aws:dynamodb:us-east-1:293839420735:table/YourTableName because no identity-based policy allows the dynamodb:PutItem action
I tried to hardcode table name directly:
Resource: "arn:aws:dynamodb:us-east-1:293839420735:table/YourTableName"
Also I tried to add separate role in yml file, but error the same.
What is the problem?
>Solution :
- Make sure the Lambda function is using the correct IAM role that allows the dynamodb:PutItem action. You have defined iamRoleStatements in your serverless.yml, but the IAM role for your Lambda function is not specified. Add the role property under the provider section:
provider:
...
role: LambdaRole
resources:
Resources:
LambdaRole:
Type: AWS::IAM::Role
Properties:
RoleName: your-pet-project-dev-us-east-1-lambdaRole
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action: sts:AssumeRole
Policies:
- PolicyName: LambdaDynamoDBPolicy
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- dynamodb:PutItem
Resource: "
-
Ensure that the table name in the error message matches the table name specified in your serverless.yml. In the provided error message, the table name is YourTableName, but in the serverless.yml file, it’s MyTestTable. Make sure they match.
-
Check if your AWS credentials are correctly set up. If you have multiple AWS profiles, ensure that the correct profile is being used by the Serverless Framework. You can specify the profile in the serverless.yml:
provider:
...
profile: your-aws-profile-name
After making these adjustments, redeploy your application using the sls deploy command, and test your Lambda function again. If you still face issues, check the IAM role and policies in the AWS Management Console to ensure that the required permissions are granted.