For an AWS Lambda function to be able to perform operations on a DynamoDB table, we need to attach an IAM policy to its "execution role" in the configuration.
Steps to attach a policy to the Lambda Function
1. Access the Lambda Function
Access the Lambda function that you want to have access to the DynamoDB table. It will have the following tabs as shown in the picture.
2. Accessing the Execution Role
Now, got to the configurations section using the "Configuration" tab. And select "Permissions" in the sidebar. This will show you the "Execution role" attached to this Lambda Function. Clicking on the link will take you to the "IAM permission policies" page of the function.
3. Create/Attach New Policy
Here, we can attach new permission to the role. Click on the "Add permissions" menu and select "Create inline policy".
"Create inline policy" is used to create specific access which we want to give to the role. "Attach policies" can be used to give a predefined set of permissions to the role. These predefined permissions are provided by AWS based on common usecases.
4. Writing New Policy
The "create inline policy" page will have a "Visual Editor" tab and a "JSON" tab. For this example, click on the "JSON" tab and paste the below code.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"dynamodb:*"
],
"Resource": "arn:aws:dynamodb:YOUR_REGION:YOUR_ACCOUNT_NUMBER:table/YOUR_TABLE"
}
]
}
Substitute YOUR_REGION, YOUR_ACCOUNT_NUMBER and YOUR_TABLE with your relevant information.
This will enable complete access for the role to the DynamoDB table. Giving full access is never an ideal practice and is only given as a simple example for demonstration. The best practice is always to narrow down to the exact permission requirements needed for the Lambda Function. See the example at the bottom.
The visual editor can be used to navaigate throught the services and its permissions.We can choose the "Service", allowed "Actions", along with the specific "Resources" identifying details through a visual interface..
Once all the required access has been selected, click on "Review policy"
5. Name and Create the New Policy
Here, you will need to give a name to the "Inline policy" and finally create the policy
Example of assigning specific permissions to the Lambda Function
The following JSON will only give granular access to the DynamoDB table.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"dynamodb:BatchGetItem",
"dynamodb:GetItem",
"dynamodb:Scan",
"dynamodb:Query",
"dynamodb:BatchWriteItem",
"dynamodb:PutItem",
"dynamodb:UpdateItem",
"dynamodb:DeleteItem"
],
"Resource": "arn:aws:dynamodb:YOUR_REGION:YOUR_ACCOUNT_NUMBER:table/YOUR_TABLE"
}
]
}
This is how you should be giving access to any resource in order to avoid loopholes in your application. Give access to only what is required.