Deleting Lambda Function

We will create a Lambda function that deletes all items with the specified partition key and sort key in the DynamoDB table. It also deletes the image file in the S3 bucket:

  1. Open AWS Lambda console, click Create function LambdaDeleteFunction

  2. Enter function name, e.g., book_delete

    • Select Python 3.12 for Runtime
    • Click Create function LambdaDeleteFunction
  3. Copy the following code and paste to lambda_function.py

import boto3
import json
import os
from boto3.dynamodb.conditions import Key

# AWS clients
dynamodb = boto3.resource("dynamodb")
s3 = boto3.client("s3")

# ENV
TABLE_NAME = "Books"
RESIZE_BUCKET = os.environ.get(
    "RESIZE_BUCKET",
    "book-image-resize-stores-tranvix"
)

table = dynamodb.Table(TABLE_NAME)


def get_image_name(image_url: str) -> str:
    """
    Extract file name from S3 URL
    """
    return image_url.split("/")[-1]


def lambda_handler(event, context):
    try:
        # ========= 1. Get book id from path =========
        book_id = event["pathParameters"]["id"]

        # ========= 2. Get book item (rv_id = 0) =========
        book_resp = table.get_item(
            Key={
                "id": book_id,
                "rv_id": 0
            }
        )

        if "Item" not in book_resp:
            return {
                "statusCode": 404,
                "body": json.dumps({"message": "Book not found"})
            }

        image_url = book_resp["Item"].get("image")
        image_name = get_image_name(image_url) if image_url else None

        # ========= 3. Query ALL items of this book =========
        query_resp = table.query(
            KeyConditionExpression=Key("id").eq(book_id)
        )

        items = query_resp["Items"]

        # ========= 4. Batch delete DynamoDB items =========
        with table.batch_writer() as batch:
            for item in items:
                batch.delete_item(
                    Key={
                        "id": item["id"],
                        "rv_id": item["rv_id"]
                    }
                )

        # ========= 5. Delete image from S3 resize bucket =========
        if image_name:
            s3.delete_object(
                Bucket=RESIZE_BUCKET,
                Key=image_name
            )

        return {
            "statusCode": 200,
            "body": json.dumps({"message": "Book deleted successfully"}),
            "headers": {
                "Content-Type": "application/json",
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Methods": "DELETE,OPTIONS",
                "Access-Control-Allow-Headers": "Content-Type,Authorization"
            }
        }

    except Exception as e:
        print("ERROR:", str(e))
        return {
            "statusCode": 500,
            "body": json.dumps({"message": "Delete book failed"}),
            "headers": {
                "Content-Type": "application/json",
                "Access-Control-Allow-Origin": "*"
            }
        }
  • Click Deploy LambdaDeleteFunction
  1. Function deployed successfully LambdaDeleteFunction

  2. Configure environment variables for Lambda function

    • Click Configuration tab
    • Select Environment variables from the left menu
    • Click Edit LambdaDeleteFunction
  3. Add the following environment variable:

    • RESIZE_BUCKET: bucket name for resized images (e.g., book-image-resize-stores-tranvix)
    • Click Save LambdaDeleteFunction
  4. Confirm environment variable is updated successfully LambdaDeleteFunction

  5. Grant function permission to read and delete data from DynamoDB and delete objects in S3 bucket

    • Select Permissions from the left menu
    • Click on the role that the function is using LambdaDeleteFunction
  6. On the IAM Role page, click Add permissions > Create inline policy LambdaDeleteFunction

  7. Select JSON tab and add the following policy:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "dynamodb:GetItem",
        "dynamodb:Query",
        "dynamodb:DeleteItem",
        "dynamodb:BatchWriteItem"
      ],
      "Resource": "arn:aws:dynamodb:AWS_REGION:ACCOUNT_ID:table/Books"
    },
    {
      "Effect": "Allow",
      "Action": "s3:DeleteObject",
      "Resource": "arn:aws:s3:::YOUR_BUCKET_NAME/*"
    }
  ]
}
  • Replace AWS_REGION with your region (e.g., ap-southeast-1)
  • Replace ACCOUNT_ID with your AWS account ID
  • Replace YOUR_BUCKET_NAME with your resize bucket name
  • Click Next LambdaDeleteFunction
  1. Enter policy name, e.g., LambdaBooksDeletePolicy

    • Review the configured permissions
    • Click Create policy LambdaDeleteFunction
  2. Policy created successfully and attached to role LambdaDeleteFunction