This tutorial guides you through creating an AWS Lambda function to automatically copy new files from one S3 bucket (source) to another (destination). This is an example to learn AWS Lambda and S3 integration.
- An AWS account.
- Basic knowledge of Python.
- Git installed on your machine.
- AWS CLI installed and configured (optional but recommended).
- Clone the project repository from Git.
git clone https://github.com/DhruvSavaliya94/AWS-Lambda-S3-File-Copy.git
- Navigate to the project root directory.
cd AWS-Lambda-S3-File-Copy
- Install required Python packages from requirements.txt.
pip install -r requirements.txt
- Log into AWS Management Console.
- Navigate to S3 and create two buckets: one for the source and one for the destination. Note the names of these buckets.
- Open the AccessS3SourceDestinationPolicy.json file from the project folder. This file contains the necessary permissions for the Lambda function.
- Log into the AWS Management Console and go to the IAM service.
- Navigate to Policies and click Create policy. Switch to the JSON tab.
- Copy and paste the content of AccessS3SourceDestinationPolicy.json into the JSON editor.
- Click Review policy.
- Name the policy AccessS3SourceDestinationPolicy and provide a description. Click Create policy.
- In the IAM console, navigate to Roles and click Create role.
- Choose Lambda as the trusted entity for the role.
- Click Next: Permissions.
- Search for and attach the AccessS3SourceDestinationPolicy policy you just created.
- Click Next: Review.
- Name the role (e.g., LambdaS3CopyRole) and provide a description.
- Click Create role.
- Navigate to the AWS Lambda service in the AWS Management Console.
- Click Create Function.
- Choose Author from scratch, enter a function name, and select Python as the runtime.
- Select role LambdaS3CopyRole.
- Click Create Function.
- Open the Lambda function you created earlier.
- In the Function code section, find the option to upload a file from your machine.
- Copy python code from project and past it in lambda function.
- Deploy the function by clicking Deploy.
- Your function is now ready.
- In your Lambda function, under the Configuration tab, find Environment variables.
- Add a new variable: Key as DESTINATION_BUCKET and Value as your destination bucket name.
- In your Lambda function, under the Designer section, click Add trigger.
- Select S3 from the dropdown.
- Choose your source S3 bucket and set the Event type to PUT.
- Click Add.
- Upload a file to your source S3 bucket.
- Check the destination S3 bucket to see if the file has been copied.
- Optionally, check CloudWatch logs for your Lambda function for logs and potential errors.