SDK for Ruby を使用したLambda 例 - AWSSDK コードサンプル

AWSDocAWS SDKGitHub サンプルリポジトリには、さらに多くの SDK サンプルがあります

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

SDK for Ruby を使用したLambda 例

次のコード例は、AWS SDK for Ruby with Lambda を使用してを使用してアクションを実行する方法を示しています。

アクション」は、個々のサービス関数の呼び出し方法を示すコードの抜粋です。

シナリオ」は、同じサービス内で複数の関数を呼び出して、特定のタスクを実行する方法を示すコード例です。

それぞれの例にはGitHub、へのリンクがあり、コンテキストでコードを設定および実行する方法についての説明が記載されています。

アクション

以下のコード例は、Lambda 関数を作成する方法を示しています。

SDK for Ruby
注記

他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

class LambdaWrapper attr_accessor :lambda_client def initialize @lambda_client = Aws::Lambda::Client.new @logger = Logger.new($stdout) @logger.level = Logger::WARN end # Deploys a Lambda function. # # @param function_name: The name of the Lambda function. # @param handler_name: The fully qualified name of the handler function. This # must include the file name and the function name. # @param role_arn: The IAM role to use for the function. # @param deployment_package: The deployment package that contains the function # code in .zip format. # @return: The Amazon Resource Name (ARN) of the newly created function. def create_function(function_name, handler_name, role_arn, deployment_package) response = @lambda_client.create_function({ role: role_arn.to_s, function_name:, handler: handler_name, runtime: "ruby2.7", code: { zip_file: deployment_package }, environment: { variables: { "LOG_LEVEL" => "info" } } }) @lambda_client.wait_until(:function_active_v2, { function_name: }) do |w| w.max_attempts = 5 w.delay = 5 end response rescue Aws::Lambda::Errors::ServiceException => e @logger.error("There was an error creating #{function_name}:\n #{e.message}") rescue Aws::Waiters::Errors::WaiterFailed => e @logger.error("Failed waiting for #{function_name} to activate:\n #{e.message}") end
  • API の詳細については、AWS SDK for RubyAPI CreateFunctionリファレンスのを参照してください

以下のコード例は、Lambda 関数を削除する方法を示しています。

SDK for Ruby
注記

他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

class LambdaWrapper attr_accessor :lambda_client def initialize @lambda_client = Aws::Lambda::Client.new @logger = Logger.new($stdout) @logger.level = Logger::WARN end # Deletes a Lambda function. # @param function_name: The name of the function to delete. def delete_function(function_name) print "Deleting function: #{function_name}..." @lambda_client.delete_function( function_name: ) print "Done!".green rescue Aws::Lambda::Errors::ServiceException => e @logger.error("There was an error deleting #{function_name}:\n #{e.message}") end
  • API の詳細については、AWS SDK for RubyAPI DeleteFunctionリファレンスのを参照してください

以下のコード例は、Lambda 関数を取得する方法を示しています。

SDK for Ruby
注記

他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

class LambdaWrapper attr_accessor :lambda_client def initialize @lambda_client = Aws::Lambda::Client.new @logger = Logger.new($stdout) @logger.level = Logger::WARN end # Gets data about a Lambda function. # # @param function_name: The name of the function. # @return response: The function data, or nil if no such function exists. def get_function(function_name) @lambda_client.get_function( { function_name: } ) rescue Aws::Lambda::Errors::ResourceNotFoundException => e @logger.debug("Could not find function: #{function_name}:\n #{e.message}") nil end
  • API の詳細については、AWS SDK for RubyAPI GetFunctionリファレンスのを参照してください

以下のコード例は、Lambda 関数を呼び出す方法を示しています。

SDK for Ruby
注記

他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

class LambdaWrapper attr_accessor :lambda_client def initialize @lambda_client = Aws::Lambda::Client.new @logger = Logger.new($stdout) @logger.level = Logger::WARN end # Invokes a Lambda function. # @param function_name [String] The name of the function to invoke. # @param payload [nil] Payload containing runtime parameters. # @return [Object] The response from the function invocation. def invoke_function(function_name, payload = nil) params = { function_name: } params[:payload] = payload unless payload.nil? @lambda_client.invoke(params) rescue Aws::Lambda::Errors::ServiceException => e @logger.error("There was an error executing #{function_name}:\n #{e.message}") end
  • API の詳細については、「AWS SDK for Ruby API リファレンス」の「[Invoke]」(呼び出し) を参照してください。

以下のコード例は、Lambda 関数を一覧表示する方法を示しています。

SDK for Ruby
注記

他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

class LambdaWrapper attr_accessor :lambda_client def initialize @lambda_client = Aws::Lambda::Client.new @logger = Logger.new($stdout) @logger.level = Logger::WARN end # Lists the Lambda functions for the current account. def list_functions functions = [] @lambda_client.list_functions.each do |response| response["functions"].each do |function| functions.append(function["function_name"]) end end functions rescue Aws::Lambda::Errors::ServiceException => e @logger.error("There was an error executing #{function_name}:\n #{e.message}") end
  • API の詳細については、AWS SDK for RubyAPI ListFunctionsリファレンスのを参照してください

以下のコード例は、Lambda 関数を更新する方法を示しています。

SDK for Ruby
注記

他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

class LambdaWrapper attr_accessor :lambda_client def initialize @lambda_client = Aws::Lambda::Client.new @logger = Logger.new($stdout) @logger.level = Logger::WARN end # Updates the code for a Lambda function by submitting a .zip archive that contains # the code for the function. # @param function_name: The name of the function to update. # @param deployment_package: The function code to update, packaged as bytes in # .zip format. # @return: Data about the update, including the status. def update_function_code(function_name, deployment_package) @lambda_client.update_function_code( function_name:, zip_file: deployment_package ) @lambda_client.wait_until(:function_updated_v2, { function_name: }) do |w| w.max_attempts = 5 w.delay = 5 end rescue Aws::Lambda::Errors::ServiceException => e @logger.error("There was an error updating function code for: #{function_name}:\n #{e.message}") nil rescue Aws::Waiters::Errors::WaiterFailed => e @logger.error("Failed waiting for #{function_name} to update:\n #{e.message}") end
  • API の詳細については、AWS SDK for RubyAPI UpdateFunctionCodeリファレンスのを参照してください

以下のコード例は、Lambda 関数の設定を更新する方法を示しています。

SDK for Ruby
注記

他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

class LambdaWrapper attr_accessor :lambda_client def initialize @lambda_client = Aws::Lambda::Client.new @logger = Logger.new($stdout) @logger.level = Logger::WARN end # Updates the environment variables for a Lambda function. # @param function_name: The name of the function to update. # @param log_level: The log level of the function. # @return: Data about the update, including the status. def update_function_configuration(function_name, log_level) @lambda_client.update_function_configuration({ function_name:, environment: { variables: { "LOG_LEVEL" => log_level } } }) @lambda_client.wait_until(:function_updated_v2, { function_name: }) do |w| w.max_attempts = 5 w.delay = 5 end rescue Aws::Lambda::Errors::ServiceException => e @logger.error("There was an error updating configurations for #{function_name}:\n #{e.message}") rescue Aws::Waiters::Errors::WaiterFailed => e @logger.error("Failed waiting for #{function_name} to activate:\n #{e.message}") end

シナリオ

次のコード例は、以下の操作方法を示しています。

  • IAM ロールと Lambda 関数を作成し、ハンドラーコードをアップロードします。

  • 1 つのパラメーターで関数を呼び出して、結果を取得します。

  • 関数コードを更新し、環境変数で設定します。

  • 新しいパラメーターで関数を呼び出して、結果を取得します。返された実行ログを表示します。

  • アカウントの関数を一覧表示し、リソースをクリーンアップします。

詳細については、「コンソールで Lambda 関数を作成する」を参照してください。

SDK for Ruby
注記

他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

ログを書き込むことができる Lambda 関数に前提条件となる IAM アクセス権限を設定します。

# Get an AWS Identity and Access Management (IAM) role. # # @param iam_role_name: The name of the role to retrieve. # @param action: Whether to create or destroy the IAM apparatus. # @return: The IAM role. def manage_iam(iam_role_name, action) role_policy = { 'Version': "2012-10-17", 'Statement': [ { 'Effect': "Allow", 'Principal': { 'Service': "lambda.amazonaws.com" }, 'Action': "sts:AssumeRole" } ] } case action when "create" role = $iam_client.create_role( role_name: iam_role_name, assume_role_policy_document: role_policy.to_json ) $iam_client.attach_role_policy( { policy_arn: "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole", role_name: iam_role_name } ) $iam_client.wait_until(:role_exists, { role_name: iam_role_name }) do |w| w.max_attempts = 5 w.delay = 5 end @logger.debug("Successfully created IAM role: #{role['role']['arn']}") @logger.debug("Enforcing a 10-second sleep to allow IAM role to activate fully.") sleep(10) return role, role_policy.to_json when "destroy" $iam_client.detach_role_policy( { policy_arn: "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole", role_name: iam_role_name } ) $iam_client.delete_role( role_name: iam_role_name ) @logger.debug("Detached policy & deleted IAM role: #{iam_role_name}") else raise "Incorrect action provided. Must provide 'create' or 'destroy'" end rescue Aws::Lambda::Errors::ServiceException => e @logger.error("There was an error creating role or attaching policy:\n #{e.message}") end

呼び出しパラメータとして指定された数値を増やす Lambda ハンドラーを定義します。

require "logger" # A function that increments a whole number by one (1) and logs the result. # Requires a manually-provided runtime parameter, 'number', which must be Int # # @param event [Hash] Parameters sent when the function is invoked # @param context [Hash] Methods and properties that provide information # about the invocation, function, and execution environment. # @return incremented_number [String] The incremented number. def lambda_handler(event:, context:) logger = Logger.new($stdout) log_level = ENV["LOG_LEVEL"] logger.level = case log_level when "debug" Logger::DEBUG when "info" Logger::INFO else Logger::ERROR end logger.debug("This is a debug log message.") logger.info("This is an info log message. Code executed successfully!") number = event["number"].to_i incremented_number = number + 1 logger.info("You provided #{number.round} and it was incremented to #{incremented_number.round}") incremented_number.round.to_s end

Lambda 関数のデプロイパッケージを圧縮します。

# Creates a Lambda deployment package in .zip format. # This zip can be passed directly as a string to Lambda when creating the function. # # @param source_file: The name of the object, without suffix, for the Lambda file and zip. # @return: The deployment package. def create_deployment_package(source_file) Dir.chdir(File.dirname(__FILE__)) if File.exist?("lambda_function.zip") File.delete("lambda_function.zip") @logger.debug("Deleting old zip: lambda_function.zip") end Zip::File.open("lambda_function.zip", create: true) { |zipfile| zipfile.add("lambda_function.rb", "#{source_file}.rb") } @logger.debug("Zipping #{source_file}.rb into: lambda_function.zip.") File.read("lambda_function.zip").to_s rescue StandardError => e @logger.error("There was an error creating deployment package:\n #{e.message}") end

新しい Lambda 関数の作成

# Deploys a Lambda function. # # @param function_name: The name of the Lambda function. # @param handler_name: The fully qualified name of the handler function. This # must include the file name and the function name. # @param role_arn: The IAM role to use for the function. # @param deployment_package: The deployment package that contains the function # code in .zip format. # @return: The Amazon Resource Name (ARN) of the newly created function. def create_function(function_name, handler_name, role_arn, deployment_package) response = @lambda_client.create_function({ role: role_arn.to_s, function_name:, handler: handler_name, runtime: "ruby2.7", code: { zip_file: deployment_package }, environment: { variables: { "LOG_LEVEL" => "info" } } }) @lambda_client.wait_until(:function_active_v2, { function_name: }) do |w| w.max_attempts = 5 w.delay = 5 end response rescue Aws::Lambda::Errors::ServiceException => e @logger.error("There was an error creating #{function_name}:\n #{e.message}") rescue Aws::Waiters::Errors::WaiterFailed => e @logger.error("Failed waiting for #{function_name} to activate:\n #{e.message}") end

オプションのランタイムパラメータを使用して Lambda 関数を呼び出します。

# Invokes a Lambda function. # @param function_name [String] The name of the function to invoke. # @param payload [nil] Payload containing runtime parameters. # @return [Object] The response from the function invocation. def invoke_function(function_name, payload = nil) params = { function_name: } params[:payload] = payload unless payload.nil? @lambda_client.invoke(params) rescue Aws::Lambda::Errors::ServiceException => e @logger.error("There was an error executing #{function_name}:\n #{e.message}") end

Lambda 関数の設定を更新して、新しい環境変数を挿入します。

# Updates the environment variables for a Lambda function. # @param function_name: The name of the function to update. # @param log_level: The log level of the function. # @return: Data about the update, including the status. def update_function_configuration(function_name, log_level) @lambda_client.update_function_configuration({ function_name:, environment: { variables: { "LOG_LEVEL" => log_level } } }) @lambda_client.wait_until(:function_updated_v2, { function_name: }) do |w| w.max_attempts = 5 w.delay = 5 end rescue Aws::Lambda::Errors::ServiceException => e @logger.error("There was an error updating configurations for #{function_name}:\n #{e.message}") rescue Aws::Waiters::Errors::WaiterFailed => e @logger.error("Failed waiting for #{function_name} to activate:\n #{e.message}") end

Lambda 関数のコードを、別のコードを含む別のデプロイパッケージで更新します。

# Updates the code for a Lambda function by submitting a .zip archive that contains # the code for the function. # @param function_name: The name of the function to update. # @param deployment_package: The function code to update, packaged as bytes in # .zip format. # @return: Data about the update, including the status. def update_function_code(function_name, deployment_package) @lambda_client.update_function_code( function_name:, zip_file: deployment_package ) @lambda_client.wait_until(:function_updated_v2, { function_name: }) do |w| w.max_attempts = 5 w.delay = 5 end rescue Aws::Lambda::Errors::ServiceException => e @logger.error("There was an error updating function code for: #{function_name}:\n #{e.message}") nil rescue Aws::Waiters::Errors::WaiterFailed => e @logger.error("Failed waiting for #{function_name} to update:\n #{e.message}") end

組み込みのペジネーターを使用して、既存のすべての Lambda 関数を一覧表示します。

# Lists the Lambda functions for the current account. def list_functions functions = [] @lambda_client.list_functions.each do |response| response["functions"].each do |function| functions.append(function["function_name"]) end end functions rescue Aws::Lambda::Errors::ServiceException => e @logger.error("There was an error executing #{function_name}:\n #{e.message}") end

特定の Lambda 関数を削除します。

# Deletes a Lambda function. # @param function_name: The name of the function to delete. def delete_function(function_name) print "Deleting function: #{function_name}..." @lambda_client.delete_function( function_name: ) print "Done!".green rescue Aws::Lambda::Errors::ServiceException => e @logger.error("There was an error deleting #{function_name}:\n #{e.message}") end