Skip to main content

Trigger an AWS Lambda Function from an S3 Event

Hands-On Lab

 

Photo of

Training Architect

Length

01:00:00

Difficulty

Beginner

The event ecosystem of AWS (along with its API) makes it one of the most powerful cloud platforms available. Lambda is AWS's serverless Function as a Service (FaaS) compute platform, and it can execute in response to many different events within AWS. In this hands-on lab we will create a Lambda function that will get triggered when an object is placed into an S3 bucket. Specifically, we will trigger a job within Amazon Transcribe to transcribe speech from an audio file placed into S3. No development knowledge is required for this lab, as all the code is provided, but we will take a look at the code and how it works.

What are Hands-On Labs?

Hands-On Labs are scenario-based learning environments where learners can practice without consequences. Don't compromise a system or waste money on expensive downloads. Practice real-world skills without the real-world risk, no assembly required.

Trigger an AWS Lambda Function from an S3 Event

Introduction

The event ecosystem of AWS (along with its API) makes it one of the most powerful cloud platforms available. Lambda is AWS's serverless Function as a Service (FaaS) compute platform, and it can execute in response to many different events within AWS.

In this hands-on lab we will create a Lambda function that will get triggered when an object is placed into an S3 bucket. Specifically, we will trigger a job within Amazon Transcribe to transcribe speech from an audio file placed into S3.

No development knowledge is required for this lab, as all the code is provided, but we will take a look at the code and how it works.

Solution

Log in to the AWS Management Console using the credentials provided, and make sure you are in the us-east-1 (N. Virginia) region throughout the lab.

All the resources for this lab, including a sample audio file, can be found on GitHub. Feel free to download the sample audio file to use for the last part of the lab.

Create IAM Role for Lambda

  1. Navigate to IAM.
  2. Click Roles from the left-hand menu.
  3. Click Create role.
  4. Select Lambda as the trusted entity.
  5. Click Next: Permissions.
  6. On the permissions policies page, search for (in the Filter policies box) and select each of the following managed policies:
    • AmazonS3ReadOnlyAccess
    • AmazonTranscribeFullAccess
    • CloudWatchLogsFullAccess
  7. Click Next: Tags.
  8. Add the following tag:
    • Key: creator
    • Value: Enter your name
  9. Click Next: Review.
  10. Enter a Role name of "lab-lambda-role".
  11. Click Create role.

Create a Lambda Function

  1. Navigate to Lambda.

  2. Click Create a function.

  3. With Author from scratch selected, and then use the following settings:

    • Function name: lab-lambda-transcribe
    • Runtime: Python 3.6
  4. Expand Choose or create an execution role, and use the following settings:

    • Execution role: Use an existing role
    • Existing role: lab-lambda-role
  5. Click Create function.

  6. In the Function code section, delete the existing code and paste in the following (also found on GitHub):

    import boto3
    import uuid
    import json
    
    def lambda_handler(event, context):
    
        print(json.dumps(event))
    
        record = event['Records'][0]
    
        s3bucket = record['s3']['bucket']['name']
        s3object = record['s3']['object']['key']
    
        s3Path = "s3://" + s3bucket + "/" + s3object
        jobName = s3object + '-' + str(uuid.uuid4())
    
        client = boto3.client('transcribe')
    
        response = client.start_transcription_job(
            TranscriptionJobName=jobName,
            LanguageCode='en-US',
            MediaFormat='mp4',
            Media={
                'MediaFileUri': s3Path
            }
        )
    
        print(json.dumps(response, default=str))
    
        return {
            'TranscriptionJobName': response['TranscriptionJob']['TranscriptionJobName']
        }
  7. Click Save.

Create a Trigger for the Lambda Function

  1. Navigate to S3.
  2. Click to open the input-... bucket.
  3. Click the Properties tab.
  4. Click the Events card.
  5. Click Add notification, and set the following properties:
    • Name: transcribe
    • Events: All object create events
    • Send to: Lambda Function
    • Lambda: lab-lambda-transcribe
    • Click Save.

Test the Architecture

  1. Head back to the bucket.
  2. Click Upload.
  3. Select and upload the sample audio file downloaded from GitHub or another .mp4 file on your machine. (It must be an .mp4 file.)
  4. Navigate to Lambda.
  5. Click our function name.
  6. Click Monitoring, where we should see CloudWatch metric populate.
  7. Click View logs in CloudWatch.
  8. Click the listed log stream. We should then see the beginning and end of when our Lambda function ran, as well as the final report (including how many milliseconds it took).
  9. Navigate to Amazon Transcribe.
  10. Click Transcription jobs in the left-hand menu.
  11. Click to open the listed transcription job.
  12. Click the output URL.
  13. Download the output file, and open the file to view the transcription.

Conclusion

Congratulations on successfully completing this hands-on lab!