Sitemap

AWS: Lambda, S3, DynamoDB, CLI

4 min readMar 30, 2016

I was speaking to someone recently who stated that he was trying to extract EXIF data from some images that he had. Now, there are many ways to skin this cat but I was working with AWS at the time and thought that this would be an opportunity to try my hand at a proof of concept. Now, the code below is by no means production ready and would take some work to make it really usable but I’m hopeful that it provides the necessary information for you to follow my logic and enough code for you to build from it.

Workflow

The workflow is as follows:

  • User uploads a jpg into a bucket on S3
  • A Lambda function kicks off and extracts EXIF information
  • This EXIF information is then loaded into DynamoDB

Most of this was created using CLI beause it is easier to document and replicate. However, there were a couple of items that I did use the web front end for and they are noted below.

DynamoDB

I used the web front end for this because I wanted to see how it worked. There is an easy CLI command to create this but since I didn’t use it I am not documenting it here.

Table: CreateThumbnailEXIF

Key: imageName (String)

Lambda

Here is where I used my CLI skilz….

First, some variables

source_bucket=christopherryanimage
target_bucket=${source_bucket}resized
function=ExtractEXIF
lambda_execution_role_name=lambda-$function-execution
lambda_execution_access_policy_name=lambda-$function-execution-access
lambda_invocation_role_name=lambda-$function-invocation
lambda_invocation_access_policy_name=lambda-$function-invocation-access
log_group_name=/aws/lambda/$function

Next, we need to get an image that contains EXIF information. We will also copy it up to our bucket. Why is it called HappyFace.jpg? Because that’s what the AWS image-resize tutorial used so I went with it for this first image.

wget -q -OHappyFace.jpg ‘http://ptforum.photoolsweb.com/ubbthreads.php?ubb=download&Number=1024&filename=1024-2006_1011_093752.jpg'aws s3 cp HappyFace.jpg s3://$source_bucket/

You will need to set up a Python virtual environment and install Pillow and exifread. I’ll leave it to you to do that (it is well documented elsewhere).

Get Christopher A. Ryan’s stories in your inbox

Join Medium for free to get updates from this writer.

Create the actual Create_Thumbnail.py Lambda python file that will be executed on the AWS servers:

from __future__ import print_function
import boto3
import os
import sys
import uuid
from PIL import Image
import PIL.Image
from PIL.ExifTags import TAGS
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
s3_client = boto3.client(‘s3’)
db_client = boto3.client(‘dynamodb’)
def resize_image(image_path, resized_path):
with Image.open(image_path) as image:
image.thumbnail(tuple(x / 2 for x in image.size))
image.save(resized_path)
def get_exif(fn, key, bucket):
ret = {}
i = Image.open(fn)
info = i._getexif()
for tag, value in info.items():
decoded = TAGS.get(tag, tag)
ret[decoded] = value
db_client.put_item(TableName=’CreateThumbnailEXIF’, Item={
‘imageName’:{‘S’:key},
‘image’:{‘S’:key},
‘LightSource’:{‘S’: str(ret[‘LightSource’])},
‘ResolutionUnit’:{‘S’: str(ret[‘ResolutionUnit’])},
‘Flash’:{‘S’: str(ret[‘Flash’])},
‘ExifVersion’:{‘S’: str(ret[‘ExifVersion’])},
‘ExposureBiasValue’:{‘S’: str(ret[‘ExposureBiasValue’])},
})
for k, v in ret.items():
print(k, v)
return ret
def handler(event, context):
logger.info(‘got event{}’.format(event))
logger.info(‘got context{}’.format(context))
for record in event[‘Records’]:
bucket = record[‘s3’][‘bucket’][‘name’]
key = record[‘s3’][‘object’][‘key’]
download_path = ‘/tmp/{}{}’.format(uuid.uuid4(), key)
upload_path = ‘/tmp/resized-{}’.format(key)
s3_client.download_file(bucket, key, download_path)
get_exif(download_path, key, bucket)
#resize_image(download_path, upload_path)
#s3_client.upload_file(upload_path, ‘{}resized’.format(bucket), key)

Zip up the files and place them on the AWS server. Below are the commands to create the necessary IAM roles and policies.

zip -r $function.zip *lambda_execution_role_arn=$(aws iam create-role \
--role-name “$lambda_execution_role_name” \
--assume-role-policy-document ‘{
“Version”: “2012–10–17”,
“Statement”: [
{
“Sid”: “”,
“Effect”: “Allow”,
“Principal”: {
“Service”: “lambda.amazonaws.com”
},
“Action”: “sts:AssumeRole”
}
]
}’ \
--output text \
--query ‘Role.Arn’
)
aws iam put-role-policy \
--role-name “$lambda_execution_role_name” \
--policy-name “$lambda_execution_access_policy_name” \
--policy-document ‘{
“Version”: “2012–10–17”,
“Statement”: [
{
“Effect”: “Allow”,
“Action”: [
“logs:*”
],
“Resource”: “arn:aws:logs:*:*:*”
},
{
“Effect”: “Allow”,
“Action”: [
“s3:GetObject”
],
“Resource”: “arn:aws:s3:::’$source_bucket’/*”
},
{
“Effect”: “Allow”,
“Action”: [
“s3:PutObject”
],
“Resource”: “arn:aws:s3:::’$target_bucket’/*”
}
]
}’
aws lambda create-function \
--region us-west-2 \
--function-name $function \
--zip-file fileb://$function.zip \
--role $lambda_execution_role_arn \
--handler $function.handler \
--runtime python2.7 \
--profile adminuser \
--timeout 10 \
--memory-size 1024

S3 Buckets

This was the first task and it required the web front end. I could not find any way in the CLI to create these buckets and assign them to the us-west-2 region. So, I gave up and grabbed my mouse.

You will need two buckets. One of them is called “whatever” and the other one has “resized” added to the original bucket as a suffix. Why two buckets? Because I was also playing around with resizing the images and that code came from AWS tutorials. I figured I would leave it in this document so you could see where I was going with it.

Next, make sure that your Lambda function executes when you add a file to the image bucket.

That’s it. Now you should see the DynamoDB tables populate with data for each image you add to the image bucket. You can also see that adding the resize functionality is very simple at this point.

--

--