In this lab, we will learn how to use environment variables in a Lambda function.
- Overview
- S3
- Create a bucket
- Upload a image file
- Lambda – Function
- Get the bucket name and the image name from environment variables
- Retrieves the object properties
- Python, boto3
1. S3 – Create a bucket
- Click “Create bucket”
- Bucket name: unique name of your choice, such as “my-bucket-2022-12-31“
- Accept all defaults and click “Create bucket“
- Click the bucket name you just created
- Click “Upload” and upload any image file
2. IAM – Setup the Lambda execution role
- Click “Roles” on the left pane
- Click “Create role“
- Trusted entity type
- Select “AWS service“
- Use case
- Select “Lambda“
- Add Permissions
- Search “CloudWatchLogsFullAccess” and select it
- Search “AmazonS3ReadOnlyAccess” and select it
- Name, review
- Role name: “LambdaS3ExecutionRole“
- Click “Create role“
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"logs:*"
],
"Effect": "Allow",
"Resource": "*"
}
]
}
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:Get*",
"s3:List*",
"s3-object-lambda:Get*",
"s3-object-lambda:List*"
],
"Resource": "*"
}
]
}
3. Lambda – Create a Function
- Function Name: “GetS3Object“
- Runtime: Python 3.9
- Permissions – Change default execution role
- Check “Use an existing role“
- Select “LambdaS3ExecutionRole“
- Click “Create function“
4. Lambda – Function Code (Python)
- Type the following code
- Click “Deploy“
import json
import logging
import os
import boto3
logger = logging.getLogger()
logger.setLevel(logging.INFO)
client = boto3.client('s3')
def lambda_handler(event, context):
bucketName = os.environ['BucketName']
imageName = os.environ['FileName']
logger.info(bucketName + ' ' + imageName)
response = client.get_object(
Bucket = bucketName,
Key = imageName,
)
logger.info(response)
5. Lambda – Set the default environment variables
- Click the “Configuration” tab
- Click “Environment variables“
- Click “Edit“
- Click “Add environment variable”
- Key: “BucketName”
- Name: “{your bucket name}“
- Click “Add environment variable”
- Key: “FileName“
- Value: “{your file name}“
6. Lambda – Test
- Click the “Test” tab
- Name: “greeting-queue“
- Select “Create new event”
- Event name: “LambdaEnvTest“
- Accept all default settings
- Click “Save“
- Click “Test“
7. CouldWatch – Check the Lambda logs
- On the Lambda function page, click the “Monitor” tab
- Check some metrics on the page
- Click the “View logs in the CloudWatch” button
- On the CloudWatch page, click the “Log stream“
- Check the logs