Working with layers for Ruby Lambda functions - Amazon Lambda
Services or capabilities described in Amazon Web Services documentation might vary by Region. To see the differences applicable to the China Regions, see Getting Started with Amazon Web Services in China (PDF).

Working with layers for Ruby Lambda functions

Use Lambda layers to package code and dependencies that you want to reuse across multiple functions. Layers usually contain library dependencies, a custom runtime, or configuration files. Creating a layer involves three general steps:

  1. Package your layer content. This means creating a .zip file archive that contains the dependencies you want to use in your functions.

  2. Create the layer in Lambda.

  3. Add the layer to your functions.

Package your layer content

To create a layer, bundle your packages into a .zip file archive that meets the following requirements:

  • Create the layer using the same Ruby version that you plan to use for the Lambda function. For example, if you create your layer for Ruby 3.4, use the Ruby 3.4 runtime for your function.

  • Your layer's .zip file must use one of these directory structures:

    • ruby/gems/x.x.x (where x.x.x is your Ruby version, for example 3.4.0)

    • ruby/lib

    For more information, see Layer paths for each Lambda runtime.

  • The packages in your layer must be compatible with Linux. Lambda functions run on Amazon Linux.

You can create layers that contain either third-party Ruby gems or your own Ruby modules and classes. Many popular Ruby gems contain native extensions (C code) that must be compiled for the Lambda Linux environment.

Pure Ruby gems contain only Ruby code and don't require compilation. These gems are simpler to package and work across different platforms.

To create a layer using pure Ruby gems
  1. Create a Gemfile to specify the pure Ruby gems you want to include in your layer:

    Example Gemfile
    source 'https://rubygems.org' gem 'tzinfo'
  2. Install the gems to vendor/bundle directory using Bundler:

    bundle config set --local path vendor/bundle bundle install
  3. Copy the installed gems to the directory structure that Lambda requires ruby/gems/3.4.0):

    mkdir -p ruby/gems/3.4.0 cp -r vendor/bundle/ruby/3.4.0*/* ruby/gems/3.4.0/
  4. Zip the layer content:

    Linux/macOS
    zip -r layer.zip ruby/
    PowerShell
    Compress-Archive -Path .\ruby -DestinationPath .\layer.zip

    The directory structure of your .zip file should look like this:

    ruby/              
    └── gems/
        └── 3.4.0/
            ├── gems/
            │   ├── concurrent-ruby-1.3.5/
            │   └── tzinfo-2.0.6/
            ├── specifications/
            ├── cache/
            ├── build_info/
            └── (other bundler directories)
    Note

    You must require each gem individually in your function code. You can't use bundler/setup or Bundler.require. For more information, see Using gems from layers in a function.

Many popular Ruby gems contain native extensions (C code) that must be compiled for the target platform. Popular gems with native extensions include nokogiri, pg, mysql2, sqlite3, and ffi. These gems must be built in a Linux environment that is compatible with the Lambda runtime.

To create a layer using gems with native extensions
  1. Create a Gemfile.

    Example Gemfile
    source 'https://rubygems.org' gem 'nokogiri' gem 'httparty'
  2. Use Docker to build the gems in a Linux environment that is compatible with Lambda. Specify an Amazon base image in your Dockerfile:

    Example Dockerfile for Ruby 3.4
    FROM public.ecr.aws/lambda/ruby:3.4 # Copy Gemfile COPY Gemfile ./ # Install system dependencies for native extensions RUN dnf update -y && \ dnf install -y gcc gcc-c++ make # Configure bundler and install gems RUN bundle config set --local path vendor/bundle && \ bundle install # Create the layer structure RUN mkdir -p ruby/gems/3.4.0 && \ cp -r vendor/bundle/ruby/3.4.0*/* ruby/gems/3.4.0/ # Create the layer zip file RUN zip -r layer.zip ruby/
  3. Build the image and extract the layer:

    docker build -t ruby-layer-builder . docker run --rm -v $(pwd):/output --entrypoint cp ruby-layer-builder layer.zip /output/

    This builds the gems in the correct Linux environment and copies the layer.zip file to your local directory. The directory structure of your .zip file should look like this:

    ruby/
    └── gems/
        └── 3.4.0/
            ├── gems/
            │   ├── bigdecimal-3.2.2/
            │   ├── csv-3.3.5/
            │   ├── httparty-0.23.1/
            │   ├── mini_mime-1.1.5/
            │   ├── multi_xml-0.7.2/
            │   ├── nokogiri-1.18.8-x86_64-linux-gnu/
            │   └── racc-1.8.1/
            ├── build_info/
            ├── cache/
            ├── specifications/
            └── (other bundler directories)
    Note

    You must require each gem individually in your function code. You can't use bundler/setup or Bundler.require. For more information, see Using gems from layers in a function.

To create a layer using your own code
  1. Create the required directory structure for your layer:

    mkdir -p ruby/lib
  2. Create your Ruby modules in the ruby/lib directory. The following example module validates orders by confirming that they contain the required information.

    Example ruby/lib/order_validator.rb
    require 'json' module OrderValidator class ValidationError < StandardError; end def self.validate_order(order_data) # Validates an order and returns formatted data required_fields = %w[product_id quantity] # Check required fields missing_fields = required_fields.reject { |field| order_data.key?(field) } unless missing_fields.empty? raise ValidationError, "Missing required fields: #{missing_fields.join(', ')}" end # Validate quantity quantity = order_data['quantity'] unless quantity.is_a?(Integer) && quantity > 0 raise ValidationError, 'Quantity must be a positive integer' end # Format and return the validated data { 'product_id' => order_data['product_id'].to_s, 'quantity' => quantity, 'shipping_priority' => order_data.fetch('priority', 'standard') } end def self.format_response(status_code, body) # Formats the API response { statusCode: status_code, body: JSON.generate(body) } end end
  3. Zip the layer content:

    Linux/macOS
    zip -r layer.zip ruby/
    PowerShell
    Compress-Archive -Path .\ruby -DestinationPath .\layer.zip

    The directory structure of your .zip file should look like this:

    ruby/              
    └── lib/
        └── order_validator.rb
  4. In your function, require and use the modules. You must require each gem individually in your function code. You can't use bundler/setup or Bundler.require. For more information, see Using gems from layers in a function. Example:

    require 'json' require 'order_validator' def lambda_handler(event:, context:) begin # Parse the order data from the event body order_data = JSON.parse(event['body'] || '{}') # Validate and format the order validated_order = OrderValidator.validate_order(order_data) OrderValidator.format_response(200, { message: 'Order validated successfully', order: validated_order }) rescue OrderValidator::ValidationError => e OrderValidator.format_response(400, { error: e.message }) rescue => e OrderValidator.format_response(500, { error: 'Internal server error' }) end end

    You can use the following test event to invoke the function:

    { "body": "{\"product_id\": \"ABC123\", \"quantity\": 2, \"priority\": \"express\"}" }

    Expected response:

    { "statusCode": 200, "body": "{\"message\":\"Order validated successfully\",\"order\":{\"product_id\":\"ABC123\",\"quantity\":2,\"shipping_priority\":\"express\"}}" }

Create the layer in Lambda

You can publish your layer using either the Amazon CLI or the Lambda console.

Amazon CLI

Run the publish-layer-version Amazon CLI command to create the Lambda layer:

aws lambda publish-layer-version --layer-name my-layer --zip-file fileb://layer.zip --compatible-runtimes ruby3.4

The compatible runtimes parameter is optional. When specified, Lambda uses this parameter to filter layers in the Lambda console.

Console
To create a layer (console)
  1. Open the Layers page of the Lambda console.

  2. Choose Create layer.

  3. Choose Upload a .zip file, and then upload the .zip archive that you created earlier.

  4. (Optional) For Compatible runtimes, choose the Ruby runtime that corresponds to the Ruby version you used to build your layer.

  5. Choose Create.

Using gems from layers in a function

In your function code, you must explicitly require each gem that you want to use. Bundler commands such as bundler/setup and Bundler.require are not supported. Here's how to properly use gems from a layer in a Lambda function:

# Correct: Use explicit requires for each gem require 'nokogiri' require 'httparty' def lambda_handler(event:, context:) # Use the gems directly doc = Nokogiri::HTML(event['html']) response = HTTParty.get(event['url']) # ... rest of your function end # Incorrect: These Bundler commands will not work # require 'bundler/setup' # Bundler.require

Add the layer to your function

Amazon CLI

To attach the layer to your function, run the update-function-configuration Amazon CLI command. For the --layers parameter, use the layer ARN. The ARN must specify the version (for example, arn:aws:lambda:us-east-1:123456789012:layer:my-layer:1). For more information, see Layers and layer versions.

aws lambda update-function-configuration --function-name my-function --cli-binary-format raw-in-base64-out --layers "arn:aws:lambda:us-east-1:123456789012:layer:my-layer:1"

The cli-binary-format option is required if you're using Amazon CLI version 2. To make this the default setting, run aws configure set cli-binary-format raw-in-base64-out. For more information, see Amazon CLI supported global command line options in the Amazon Command Line Interface User Guide for Version 2.

Console
To add a layer to a function
  1. Open the Functions page of the Lambda console.

  2. Choose the function.

  3. Scroll down to the Layers section, and then choose Add a layer.

  4. Under Choose a layer, select Custom layers, and then choose your layer.

    Note

    If you didn't add a compatible runtime when you created the layer, your layer won't be listed here. You can specify the layer ARN instead.

  5. Choose Add.

Sample app

For more examples of how to use Lambda layers, see the layer-ruby sample application in the Amazon Lambda Developer Guide GitHub repository. This application includes a layer that contains the tzinfo library. After creating the layer, you can deploy and invoke the corresponding function to confirm that the layer works as expected.