SDK for C++ を使用した Lambda の例 - AWS SDK コードサンプル

Doc AWS SDK Examples リポジトリには、他にも SDK の例があります。 AWS GitHub

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

SDK for C++ を使用した Lambda の例

次のコードサンプルは、Lambda で AWS SDK for C++ を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

アクションはより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、関連するシナリオやサービス間の例ではアクションのコンテキストが確認できます。

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

各例には、 へのリンクが含まれています。このリンクには GitHub、コンテキスト内でコードをセットアップして実行する方法の手順が記載されています。

開始方法

次のコード例では、Lambda の使用を開始する方法について示しています。

SDK for C++
注記

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

C MakeLists.txt CMake ファイルのコード。

# Set the minimum required version of CMake for this project. cmake_minimum_required(VERSION 3.13) # Set the AWS service components used by this project. set(SERVICE_COMPONENTS lambda) # Set this project's name. project("hello_lambda") # Set the C++ standard to use to build this target. # At least C++ 11 is required for the AWS SDK for C++. set(CMAKE_CXX_STANDARD 11) # Use the MSVC variable to determine if this is a Windows build. set(WINDOWS_BUILD ${MSVC}) if (WINDOWS_BUILD) # Set the location where CMake can find the installed libraries for the AWS SDK. string(REPLACE ";" "/aws-cpp-sdk-all;" SYSTEM_MODULE_PATH "${CMAKE_SYSTEM_PREFIX_PATH}/aws-cpp-sdk-all") list(APPEND CMAKE_PREFIX_PATH ${SYSTEM_MODULE_PATH}) endif () # Find the AWS SDK for C++ package. find_package(AWSSDK REQUIRED COMPONENTS ${SERVICE_COMPONENTS}) if (WINDOWS_BUILD) # Copy relevant AWS SDK for C++ libraries into the current binary directory for running and debugging. # set(BIN_SUB_DIR "/Debug") # if you are building from the command line you may need to uncomment this # and set the proper subdirectory to the executables' location. AWSSDK_CPY_DYN_LIBS(SERVICE_COMPONENTS "" ${CMAKE_CURRENT_BINARY_DIR}${BIN_SUB_DIR}) endif () add_executable(${PROJECT_NAME} hello_lambda.cpp) target_link_libraries(${PROJECT_NAME} ${AWSSDK_LINK_LIBRARIES})

hello_lambda.cpp ソースファイルのコード。

#include <aws/core/Aws.h> #include <aws/lambda/LambdaClient.h> #include <aws/lambda/model/ListFunctionsRequest.h> #include <iostream> /* * A "Hello Lambda" starter application which initializes an AWS Lambda (Lambda) client and lists the Lambda functions. * * main function * * Usage: 'hello_lambda' * */ int main(int argc, char **argv) { Aws::SDKOptions options; // Optionally change the log level for debugging. // options.loggingOptions.logLevel = Utils::Logging::LogLevel::Debug; Aws::InitAPI(options); // Should only be called once. int result = 0; { Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::Lambda::LambdaClient lambdaClient(clientConfig); std::vector<Aws::String> functions; Aws::String marker; // Used for pagination. do { Aws::Lambda::Model::ListFunctionsRequest request; if (!marker.empty()) { request.SetMarker(marker); } Aws::Lambda::Model::ListFunctionsOutcome outcome = lambdaClient.ListFunctions( request); if (outcome.IsSuccess()) { const Aws::Lambda::Model::ListFunctionsResult &listFunctionsResult = outcome.GetResult(); std::cout << listFunctionsResult.GetFunctions().size() << " lambda functions were retrieved." << std::endl; for (const Aws::Lambda::Model::FunctionConfiguration &functionConfiguration: listFunctionsResult.GetFunctions()) { functions.push_back(functionConfiguration.GetFunctionName()); std::cout << functions.size() << " " << functionConfiguration.GetDescription() << std::endl; std::cout << " " << Aws::Lambda::Model::RuntimeMapper::GetNameForRuntime( functionConfiguration.GetRuntime()) << ": " << functionConfiguration.GetHandler() << std::endl; } marker = listFunctionsResult.GetNextMarker(); } else { std::cerr << "Error with Lambda::ListFunctions. " << outcome.GetError().GetMessage() << std::endl; result = 1; break; } } while (!marker.empty()); } Aws::ShutdownAPI(options); // Should only be called once. return result; }
  • API の詳細については、「 API リファレンスListFunctions」の「」を参照してください。 AWS SDK for C++

アクション

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

SDK for C++
注記

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

Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region in which the bucket was created (overrides config file). // clientConfig.region = "us-east-1"; Aws::Lambda::LambdaClient client(clientConfig); Aws::Lambda::Model::CreateFunctionRequest request; request.SetFunctionName(LAMBDA_NAME); request.SetDescription(LAMBDA_DESCRIPTION); // Optional. #if USE_CPP_LAMBDA_FUNCTION request.SetRuntime(Aws::Lambda::Model::Runtime::provided_al2); request.SetTimeout(15); request.SetMemorySize(128); // Assume the AWS Lambda function was built in Docker with same architecture // as this code. #if defined(__x86_64__) request.SetArchitectures({Aws::Lambda::Model::Architecture::x86_64}); #elif defined(__aarch64__) request.SetArchitectures({Aws::Lambda::Model::Architecture::arm64}); #else #error "Unimplemented architecture" #endif // defined(architecture) #else request.SetRuntime(Aws::Lambda::Model::Runtime::python3_8); #endif request.SetRole(roleArn); request.SetHandler(LAMBDA_HANDLER_NAME); request.SetPublish(true); Aws::Lambda::Model::FunctionCode code; std::ifstream ifstream(INCREMENT_LAMBDA_CODE.c_str(), std::ios_base::in | std::ios_base::binary); if (!ifstream.is_open()) { std::cerr << "Error opening file " << INCREMENT_LAMBDA_CODE << "." << std::endl; #if USE_CPP_LAMBDA_FUNCTION std::cerr << "The cpp Lambda function must be built following the instructions in the cpp_lambda/README.md file. " << std::endl; #endif deleteIamRole(clientConfig); return false; } Aws::StringStream buffer; buffer << ifstream.rdbuf(); code.SetZipFile(Aws::Utils::ByteBuffer((unsigned char *) buffer.str().c_str(), buffer.str().length())); request.SetCode(code); Aws::Lambda::Model::CreateFunctionOutcome outcome = client.CreateFunction( request); if (outcome.IsSuccess()) { std::cout << "The lambda function was successfully created. " << seconds << " seconds elapsed." << std::endl; break; } else { std::cerr << "Error with CreateFunction. " << outcome.GetError().GetMessage() << std::endl; deleteIamRole(clientConfig); return false; }
  • API の詳細については、「 API リファレンスCreateFunction」の「」を参照してください。 AWS SDK for C++

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

SDK for C++
注記

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

Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region in which the bucket was created (overrides config file). // clientConfig.region = "us-east-1"; Aws::Lambda::LambdaClient client(clientConfig); Aws::Lambda::Model::DeleteFunctionRequest request; request.SetFunctionName(LAMBDA_NAME); Aws::Lambda::Model::DeleteFunctionOutcome outcome = client.DeleteFunction( request); if (outcome.IsSuccess()) { std::cout << "The lambda function was successfully deleted." << std::endl; } else { std::cerr << "Error with Lambda::DeleteFunction. " << outcome.GetError().GetMessage() << std::endl; }
  • API の詳細については、「 API リファレンスDeleteFunction」の「」を参照してください。 AWS SDK for C++

次のコード例では、Lambda 関数を取得する方法を示します。

SDK for C++
注記

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

Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region in which the bucket was created (overrides config file). // clientConfig.region = "us-east-1"; Aws::Lambda::LambdaClient client(clientConfig); Aws::Lambda::Model::GetFunctionRequest request; request.SetFunctionName(functionName); Aws::Lambda::Model::GetFunctionOutcome outcome = client.GetFunction(request); if (outcome.IsSuccess()) { std::cout << "Function retrieve.\n" << outcome.GetResult().GetConfiguration().Jsonize().View().WriteReadable() << std::endl; } else { std::cerr << "Error with Lambda::GetFunction. " << outcome.GetError().GetMessage() << std::endl; }
  • API の詳細については、「 API リファレンスGetFunction」の「」を参照してください。 AWS SDK for C++

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

SDK for C++
注記

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

Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region in which the bucket was created (overrides config file). // clientConfig.region = "us-east-1"; Aws::Lambda::LambdaClient client(clientConfig); Aws::Lambda::Model::InvokeRequest request; request.SetFunctionName(LAMBDA_NAME); request.SetLogType(logType); std::shared_ptr<Aws::IOStream> payload = Aws::MakeShared<Aws::StringStream>( "FunctionTest"); *payload << jsonPayload.View().WriteReadable(); request.SetBody(payload); request.SetContentType("application/json"); Aws::Lambda::Model::InvokeOutcome outcome = client.Invoke(request); if (outcome.IsSuccess()) { invokeResult = std::move(outcome.GetResult()); result = true; break; } else { std::cerr << "Error with Lambda::InvokeRequest. " << outcome.GetError().GetMessage() << std::endl; break; }
  • API の詳細については、「AWS SDK for C++ API リファレンス」の「[Invoke]」(呼び出し) を参照してください。

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

SDK for C++
注記

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

Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region in which the bucket was created (overrides config file). // clientConfig.region = "us-east-1"; Aws::Lambda::LambdaClient client(clientConfig); std::vector<Aws::String> functions; Aws::String marker; do { Aws::Lambda::Model::ListFunctionsRequest request; if (!marker.empty()) { request.SetMarker(marker); } Aws::Lambda::Model::ListFunctionsOutcome outcome = client.ListFunctions( request); if (outcome.IsSuccess()) { const Aws::Lambda::Model::ListFunctionsResult &result = outcome.GetResult(); std::cout << result.GetFunctions().size() << " lambda functions were retrieved." << std::endl; for (const Aws::Lambda::Model::FunctionConfiguration &functionConfiguration: result.GetFunctions()) { functions.push_back(functionConfiguration.GetFunctionName()); std::cout << functions.size() << " " << functionConfiguration.GetDescription() << std::endl; std::cout << " " << Aws::Lambda::Model::RuntimeMapper::GetNameForRuntime( functionConfiguration.GetRuntime()) << ": " << functionConfiguration.GetHandler() << std::endl; } marker = result.GetNextMarker(); } else { std::cerr << "Error with Lambda::ListFunctions. " << outcome.GetError().GetMessage() << std::endl; } } while (!marker.empty());
  • API の詳細については、「 API リファレンスListFunctions」の「」を参照してください。 AWS SDK for C++

次のコード例では、Lambda 関数を更新する方法を示します。

SDK for C++
注記

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

Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region in which the bucket was created (overrides config file). // clientConfig.region = "us-east-1"; Aws::Lambda::LambdaClient client(clientConfig); Aws::Lambda::Model::UpdateFunctionCodeRequest request; request.SetFunctionName(LAMBDA_NAME); std::ifstream ifstream(CALCULATOR_LAMBDA_CODE.c_str(), std::ios_base::in | std::ios_base::binary); if (!ifstream.is_open()) { std::cerr << "Error opening file " << INCREMENT_LAMBDA_CODE << "." << std::endl; #if USE_CPP_LAMBDA_FUNCTION std::cerr << "The cpp Lambda function must be built following the instructions in the cpp_lambda/README.md file. " << std::endl; #endif deleteLambdaFunction(client); deleteIamRole(clientConfig); return false; } Aws::StringStream buffer; buffer << ifstream.rdbuf(); request.SetZipFile( Aws::Utils::ByteBuffer((unsigned char *) buffer.str().c_str(), buffer.str().length())); request.SetPublish(true); Aws::Lambda::Model::UpdateFunctionCodeOutcome outcome = client.UpdateFunctionCode( request); if (outcome.IsSuccess()) { std::cout << "The lambda code was successfully updated." << std::endl; } else { std::cerr << "Error with Lambda::UpdateFunctionCode. " << outcome.GetError().GetMessage() << std::endl; }
  • API の詳細については、「 API リファレンスUpdateFunctionCode」の「」を参照してください。 AWS SDK for C++

次のコード例では、Lambda 関数の設定を更新する方法を示します。

SDK for C++
注記

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

Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region in which the bucket was created (overrides config file). // clientConfig.region = "us-east-1"; Aws::Lambda::LambdaClient client(clientConfig); Aws::Lambda::Model::UpdateFunctionConfigurationRequest request; request.SetFunctionName(LAMBDA_NAME); Aws::Lambda::Model::Environment environment; environment.AddVariables("LOG_LEVEL", "DEBUG"); request.SetEnvironment(environment); Aws::Lambda::Model::UpdateFunctionConfigurationOutcome outcome = client.UpdateFunctionConfiguration( request); if (outcome.IsSuccess()) { std::cout << "The lambda configuration was successfully updated." << std::endl; break; } else { std::cerr << "Error with Lambda::UpdateFunctionConfiguration. " << outcome.GetError().GetMessage() << std::endl; }
  • API の詳細については、「 API リファレンスUpdateFunctionConfiguration」の「」を参照してください。 AWS SDK for C++

シナリオ

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

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

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

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

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

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

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

SDK for C++
注記

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

//! Get started with functions scenario. /*! \param clientConfig: AWS client configuration. \return bool: Successful completion. */ bool AwsDoc::Lambda::getStartedWithFunctionsScenario( const Aws::Client::ClientConfiguration &clientConfig) { Aws::Lambda::LambdaClient client(clientConfig); // 1. Create an AWS Identity and Access Management (IAM) role for Lambda function. Aws::String roleArn; if (!getIamRoleArn(roleArn, clientConfig)) { return false; } // 2. Create a Lambda function. int seconds = 0; do { Aws::Lambda::Model::CreateFunctionRequest request; request.SetFunctionName(LAMBDA_NAME); request.SetDescription(LAMBDA_DESCRIPTION); // Optional. #if USE_CPP_LAMBDA_FUNCTION request.SetRuntime(Aws::Lambda::Model::Runtime::provided_al2); request.SetTimeout(15); request.SetMemorySize(128); // Assume the AWS Lambda function was built in Docker with same architecture // as this code. #if defined(__x86_64__) request.SetArchitectures({Aws::Lambda::Model::Architecture::x86_64}); #elif defined(__aarch64__) request.SetArchitectures({Aws::Lambda::Model::Architecture::arm64}); #else #error "Unimplemented architecture" #endif // defined(architecture) #else request.SetRuntime(Aws::Lambda::Model::Runtime::python3_8); #endif request.SetRole(roleArn); request.SetHandler(LAMBDA_HANDLER_NAME); request.SetPublish(true); Aws::Lambda::Model::FunctionCode code; std::ifstream ifstream(INCREMENT_LAMBDA_CODE.c_str(), std::ios_base::in | std::ios_base::binary); if (!ifstream.is_open()) { std::cerr << "Error opening file " << INCREMENT_LAMBDA_CODE << "." << std::endl; #if USE_CPP_LAMBDA_FUNCTION std::cerr << "The cpp Lambda function must be built following the instructions in the cpp_lambda/README.md file. " << std::endl; #endif deleteIamRole(clientConfig); return false; } Aws::StringStream buffer; buffer << ifstream.rdbuf(); code.SetZipFile(Aws::Utils::ByteBuffer((unsigned char *) buffer.str().c_str(), buffer.str().length())); request.SetCode(code); Aws::Lambda::Model::CreateFunctionOutcome outcome = client.CreateFunction( request); if (outcome.IsSuccess()) { std::cout << "The lambda function was successfully created. " << seconds << " seconds elapsed." << std::endl; break; } else if (outcome.GetError().GetErrorType() == Aws::Lambda::LambdaErrors::INVALID_PARAMETER_VALUE && outcome.GetError().GetMessage().find("role") >= 0) { if ((seconds % 5) == 0) { // Log status every 10 seconds. std::cout << "Waiting for the IAM role to become available as a CreateFunction parameter. " << seconds << " seconds elapsed." << std::endl; std::cout << outcome.GetError().GetMessage() << std::endl; } } else { std::cerr << "Error with CreateFunction. " << outcome.GetError().GetMessage() << std::endl; deleteIamRole(clientConfig); return false; } ++seconds; std::this_thread::sleep_for(std::chrono::seconds(1)); } while (60 > seconds); std::cout << "The current Lambda function increments 1 by an input." << std::endl; // 3. Invoke the Lambda function. { int increment = askQuestionForInt("Enter an increment integer: "); Aws::Lambda::Model::InvokeResult invokeResult; Aws::Utils::Json::JsonValue jsonPayload; jsonPayload.WithString("action", "increment"); jsonPayload.WithInteger("number", increment); if (invokeLambdaFunction(jsonPayload, Aws::Lambda::Model::LogType::Tail, invokeResult, client)) { Aws::Utils::Json::JsonValue jsonValue(invokeResult.GetPayload()); Aws::Map<Aws::String, Aws::Utils::Json::JsonView> values = jsonValue.View().GetAllObjects(); auto iter = values.find("result"); if (iter != values.end() && iter->second.IsIntegerType()) { { std::cout << INCREMENT_RESUlT_PREFIX << iter->second.AsInteger() << std::endl; } } else { std::cout << "There was an error in execution. Here is the log." << std::endl; Aws::Utils::ByteBuffer buffer = Aws::Utils::HashingUtils::Base64Decode( invokeResult.GetLogResult()); std::cout << "With log " << buffer.GetUnderlyingData() << std::endl; } } } std::cout << "The Lambda function will now be updated with new code. Press return to continue, "; Aws::String answer; std::getline(std::cin, answer); // 4. Update the Lambda function code. { Aws::Lambda::Model::UpdateFunctionCodeRequest request; request.SetFunctionName(LAMBDA_NAME); std::ifstream ifstream(CALCULATOR_LAMBDA_CODE.c_str(), std::ios_base::in | std::ios_base::binary); if (!ifstream.is_open()) { std::cerr << "Error opening file " << INCREMENT_LAMBDA_CODE << "." << std::endl; #if USE_CPP_LAMBDA_FUNCTION std::cerr << "The cpp Lambda function must be built following the instructions in the cpp_lambda/README.md file. " << std::endl; #endif deleteLambdaFunction(client); deleteIamRole(clientConfig); return false; } Aws::StringStream buffer; buffer << ifstream.rdbuf(); request.SetZipFile( Aws::Utils::ByteBuffer((unsigned char *) buffer.str().c_str(), buffer.str().length())); request.SetPublish(true); Aws::Lambda::Model::UpdateFunctionCodeOutcome outcome = client.UpdateFunctionCode( request); if (outcome.IsSuccess()) { std::cout << "The lambda code was successfully updated." << std::endl; } else { std::cerr << "Error with Lambda::UpdateFunctionCode. " << outcome.GetError().GetMessage() << std::endl; } } std::cout << "This function uses an environment variable to control the logging level." << std::endl; std::cout << "UpdateFunctionConfiguration will be used to set the LOG_LEVEL to DEBUG." << std::endl; seconds = 0; // 5. Update the Lambda function configuration. do { ++seconds; std::this_thread::sleep_for(std::chrono::seconds(1)); Aws::Lambda::Model::UpdateFunctionConfigurationRequest request; request.SetFunctionName(LAMBDA_NAME); Aws::Lambda::Model::Environment environment; environment.AddVariables("LOG_LEVEL", "DEBUG"); request.SetEnvironment(environment); Aws::Lambda::Model::UpdateFunctionConfigurationOutcome outcome = client.UpdateFunctionConfiguration( request); if (outcome.IsSuccess()) { std::cout << "The lambda configuration was successfully updated." << std::endl; break; } // RESOURCE_IN_USE: function code update not completed. else if (outcome.GetError().GetErrorType() != Aws::Lambda::LambdaErrors::RESOURCE_IN_USE) { if ((seconds % 10) == 0) { // Log status every 10 seconds. std::cout << "Lambda function update in progress . After " << seconds << " seconds elapsed." << std::endl; } } else { std::cerr << "Error with Lambda::UpdateFunctionConfiguration. " << outcome.GetError().GetMessage() << std::endl; } } while (0 < seconds); if (0 > seconds) { std::cerr << "Function failed to become active." << std::endl; } else { std::cout << "Updated function active after " << seconds << " seconds." << std::endl; } std::cout << "\nThe new code applies an arithmetic operator to two variables, x an y." << std::endl; std::vector<Aws::String> operators = {"plus", "minus", "times", "divided-by"}; for (size_t i = 0; i < operators.size(); ++i) { std::cout << " " << i + 1 << " " << operators[i] << std::endl; } // 6. Invoke the updated Lambda function. do { int operatorIndex = askQuestionForIntRange("Select an operator index 1 - 4 ", 1, 4); int x = askQuestionForInt("Enter an integer for the x value "); int y = askQuestionForInt("Enter an integer for the y value "); Aws::Utils::Json::JsonValue calculateJsonPayload; calculateJsonPayload.WithString("action", operators[operatorIndex - 1]); calculateJsonPayload.WithInteger("x", x); calculateJsonPayload.WithInteger("y", y); Aws::Lambda::Model::InvokeResult calculatedResult; if (invokeLambdaFunction(calculateJsonPayload, Aws::Lambda::Model::LogType::Tail, calculatedResult, client)) { Aws::Utils::Json::JsonValue jsonValue(calculatedResult.GetPayload()); Aws::Map<Aws::String, Aws::Utils::Json::JsonView> values = jsonValue.View().GetAllObjects(); auto iter = values.find("result"); if (iter != values.end() && iter->second.IsIntegerType()) { std::cout << ARITHMETIC_RESUlT_PREFIX << x << " " << operators[operatorIndex - 1] << " " << y << " is " << iter->second.AsInteger() << std::endl; } else if (iter != values.end() && iter->second.IsFloatingPointType()) { std::cout << ARITHMETIC_RESUlT_PREFIX << x << " " << operators[operatorIndex - 1] << " " << y << " is " << iter->second.AsDouble() << std::endl; } else { std::cout << "There was an error in execution. Here is the log." << std::endl; Aws::Utils::ByteBuffer buffer = Aws::Utils::HashingUtils::Base64Decode( calculatedResult.GetLogResult()); std::cout << "With log " << buffer.GetUnderlyingData() << std::endl; } } answer = askQuestion("Would you like to try another operation? (y/n) "); } while (answer == "y"); std::cout << "A list of the lambda functions will be retrieved. Press return to continue, "; std::getline(std::cin, answer); // 7. List the Lambda functions. std::vector<Aws::String> functions; Aws::String marker; do { Aws::Lambda::Model::ListFunctionsRequest request; if (!marker.empty()) { request.SetMarker(marker); } Aws::Lambda::Model::ListFunctionsOutcome outcome = client.ListFunctions( request); if (outcome.IsSuccess()) { const Aws::Lambda::Model::ListFunctionsResult &result = outcome.GetResult(); std::cout << result.GetFunctions().size() << " lambda functions were retrieved." << std::endl; for (const Aws::Lambda::Model::FunctionConfiguration &functionConfiguration: result.GetFunctions()) { functions.push_back(functionConfiguration.GetFunctionName()); std::cout << functions.size() << " " << functionConfiguration.GetDescription() << std::endl; std::cout << " " << Aws::Lambda::Model::RuntimeMapper::GetNameForRuntime( functionConfiguration.GetRuntime()) << ": " << functionConfiguration.GetHandler() << std::endl; } marker = result.GetNextMarker(); } else { std::cerr << "Error with Lambda::ListFunctions. " << outcome.GetError().GetMessage() << std::endl; } } while (!marker.empty()); // 8. Get a Lambda function. if (!functions.empty()) { std::stringstream question; question << "Choose a function to retrieve between 1 and " << functions.size() << " "; int functionIndex = askQuestionForIntRange(question.str(), 1, static_cast<int>(functions.size())); Aws::String functionName = functions[functionIndex - 1]; Aws::Lambda::Model::GetFunctionRequest request; request.SetFunctionName(functionName); Aws::Lambda::Model::GetFunctionOutcome outcome = client.GetFunction(request); if (outcome.IsSuccess()) { std::cout << "Function retrieve.\n" << outcome.GetResult().GetConfiguration().Jsonize().View().WriteReadable() << std::endl; } else { std::cerr << "Error with Lambda::GetFunction. " << outcome.GetError().GetMessage() << std::endl; } } std::cout << "The resources will be deleted. Press return to continue, "; std::getline(std::cin, answer); // 9. Delete the Lambda function. bool result = deleteLambdaFunction(client); // 10. Delete the IAM role. return result && deleteIamRole(clientConfig); } //! Routine which invokes a Lambda function and returns the result. /*! \param jsonPayload: Payload for invoke function. \param logType: Log type setting for invoke function. \param invokeResult: InvokeResult object to receive the result. \param client: Lambda client. \return bool: Successful completion. */ bool AwsDoc::Lambda::invokeLambdaFunction(const Aws::Utils::Json::JsonValue &jsonPayload, Aws::Lambda::Model::LogType logType, Aws::Lambda::Model::InvokeResult &invokeResult, const Aws::Lambda::LambdaClient &client) { int seconds = 0; bool result = false; /* * In this example, the Invoke function can be called before recently created resources are * available. The Invoke function is called repeatedly until the resources are * available. */ do { Aws::Lambda::Model::InvokeRequest request; request.SetFunctionName(LAMBDA_NAME); request.SetLogType(logType); std::shared_ptr<Aws::IOStream> payload = Aws::MakeShared<Aws::StringStream>( "FunctionTest"); *payload << jsonPayload.View().WriteReadable(); request.SetBody(payload); request.SetContentType("application/json"); Aws::Lambda::Model::InvokeOutcome outcome = client.Invoke(request); if (outcome.IsSuccess()) { invokeResult = std::move(outcome.GetResult()); result = true; break; } // ACCESS_DENIED: because the role is not available yet. // RESOURCE_CONFLICT: because the Lambda function is being created or updated. else if ((outcome.GetError().GetErrorType() == Aws::Lambda::LambdaErrors::ACCESS_DENIED) || (outcome.GetError().GetErrorType() == Aws::Lambda::LambdaErrors::RESOURCE_CONFLICT)) { if ((seconds % 5) == 0) { // Log status every 10 seconds. std::cout << "Waiting for the invoke api to be available, status " << ((outcome.GetError().GetErrorType() == Aws::Lambda::LambdaErrors::ACCESS_DENIED ? "ACCESS_DENIED" : "RESOURCE_CONFLICT")) << ". " << seconds << " seconds elapsed." << std::endl; } } else { std::cerr << "Error with Lambda::InvokeRequest. " << outcome.GetError().GetMessage() << std::endl; break; } ++seconds; std::this_thread::sleep_for(std::chrono::seconds(1)); } while (seconds < 60); return result; }