[AWS Lambda] Resize the image saved in S3 and save it in another S3 (using Ruby)

Target

Resize the image data saved in S3 using the Lambda function and save it in another S3. The programming language uses Ruby.

Introduction

I'm not very familiar with Lambda, so basically the purpose is to leave the basic operation of Lambda as a procedure. I tried a simple process of resizing (fixing size) the image put into S3 from the AWS console and saving it in another S3.

Premise

You have created two S3 buckets in advance.

Diagram

Untitled Diagram.png

Workflow

Item number title
1 Creating and uploading Lambda functions
2 Setting Lambda environment variables
3 Handler and execution role settings
4 Event trigger definition
5 Execution role settings
6 Operation verification

procedure

1. Create and upload Lambda functions

Select any function name and programming language to use with your Lambda function. This time, I will write it in Ruby2.5. image.png

Create a zipped version of the Lambda function body to be deployed and the external library (mini_magick). Perform the following operations on the working directory.

First, create a Gemfile

Gemfile



source 'https://rubygems.org'
gem "mini_magick"

Install the gem under the working directory using bundle install --path vendor / bundle.


bundle install --path vendor/bundle

In addition, create handler.rb which is the main body of the Lambda function.

handler.rb



require 'aws-sdk-s3'
require 'base64'
require 'mini_magick'

def resize_image(event:, context:)
  s3_client = Aws::S3::Client.new(
                           :region => ENV['REGION'],
                           :access_key_id => ENV['ACCESS_KEY'],
                           :secret_access_key => ENV['SECRET_ACCESS_KEY']
                          )
                          
  #Import the image saved from S3 specified as the event source
  key = event['Records'][0]['s3']['object']['key']
  image_file = s3_client.get_object(:bucket => ENV['BUCKET_BEFORE'], :key => key).body.read
  image = MiniMagick::Image.read(image_file)

  #Resized image in Lambda environment/Temporary write to tmp
  resized_tmp_file = "/tmp/#{key.delete("images/")}"
  image.resize("300x300").write(resized_tmp_file)

  #Upload execution
  s3_resource = Aws::S3::Resource.new()
  object = s3_resource.bucket(ENV['BUCKET_AFTER']).object(key).upload_file(resized_tmp_file)
end

Zip the handler.rb and vender.

image.png

Upload the created zip file. Click Upload .zip file from the function code field action on the Lambda console tempsnip.png

Select handler.zip andSave

tempsnip.png

2. Setting Lambda environment variables

Set the environment variables used in the Lambda function from the Lambda console.

tempsnip.png

3. Handler and execution role settings

It is said that the setting of which function to call in which file is specified by a parameter called handler. Edit the content according to the Lambda function created this time.

Click Edit for preferences on your Lambda console tempsnip.png

Enter a value in the format of executable file name (excluding extension) .function name in the handler field and save it. tempsnip.png

4. Definition of event trigger

Click Add Trigger from the Lambda console tempsnip.png

The AWS service used as the event trigger this time is S3 tempsnip.png

Make detailed settings for the trigger. This time, the event will be started when the object is created in the images directory. tempsnip.png

By putting Trigger Enabled, S3 can kick the process to this Lambda function (Lambda function policy setting). Finally click Add

tempsnip.png

5. Execution role settings

Furthermore, this time it is necessary to access S3 from Lambda when saving the resized image, so Grant an execute role with access to S3.

Click access rights at the top of the Lambda console, then click the execution role name

tempsnip.png

Click Attach Policy tempsnip.png

ʻAfter selecting AmazonS3FullAccess, Attach Policy ` tempsnip.png

6. Operation verification

Upload any image in the S3 images directory specified as the event source. image.png

By the way, the uploaded image is here image.png

When I checked S3 specified as the image save destination after resizing, the image was saved, so it's OK. image.png

The contents were also resized. image.png

You can check Lambda logs from Cloudwatch Logs. image.png

Articles that I used as a reference

Image resizing API created in 1 hour using AWS Lambda Ruby

Recommended Posts

[AWS Lambda] Resize the image saved in S3 and save it in another S3 (using Ruby)
Create and integrate Slack App and AWS Lambda (for ruby) in 30 minutes
I made a Ruby container image and moved the Lambda function
Note: Image storage using AWS S3
Easily create virtual S3 and test the integration between AWS Lambda and S3 services in your local environment
I want to download a file on the Internet using Ruby and save it locally (with caution)
Change the save destination of the image to S3 in the Rails app. Part 2
[Android development] Get an image from the server in Java and set it in ImageView! !!
[Java] Sort the list using streams and lambda expressions
Import the instance and use it on another screen
Examine the elements in the array using the [Ruby] includes? Method
About the difference between classes and instances in Ruby
Display a loading image in JavaFX and then display another image
[Ruby on Rails] I want to get the URL of the image saved in Active Storage