Ejemplos de Lambda que utilizan AWS SDK for .NET - AWS Ejemplos de código de SDK

Hay más ejemplos de AWS SDK disponibles en el GitHub repositorio de ejemplos de AWS Doc SDK.

Las traducciones son generadas a través de traducción automática. En caso de conflicto entre la traducción y la version original de inglés, prevalecerá la version en inglés.

Ejemplos de Lambda que utilizan AWS SDK for .NET

Los siguientes ejemplos de código muestran cómo realizar acciones e implementar escenarios comunes AWS SDK for .NET mediante Lambda.

Las acciones son extractos de código de programas más grandes y deben ejecutarse en contexto. Mientras las acciones muestran cómo llamar a las funciones de servicio individuales, es posible ver las acciones en contexto en los escenarios relacionados y en los ejemplos entre servicios.

Los escenarios son ejemplos de código que muestran cómo llevar a cabo una tarea específica llamando a varias funciones dentro del mismo servicio.

Cada ejemplo incluye un enlace a GitHub, donde puede encontrar instrucciones sobre cómo configurar y ejecutar el código en su contexto.

Introducción

En los siguientes ejemplos de código se muestra cómo empezar a utilizar Lambda.

AWS SDK for .NET
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

namespace LambdaActions; using Amazon.Lambda; public class HelloLambda { static async Task Main(string[] args) { var lambdaClient = new AmazonLambdaClient(); Console.WriteLine("Hello AWS Lambda"); Console.WriteLine("Let's get started with AWS Lambda by listing your existing Lambda functions:"); var response = await lambdaClient.ListFunctionsAsync(); response.Functions.ForEach(function => { Console.WriteLine($"{function.FunctionName}\t{function.Description}"); }); } }
  • Para obtener más información sobre la API, consulta ListFunctionsla Referencia AWS SDK for .NET de la API.

Acciones

En el siguiente ejemplo de código, se muestra cómo usar CreateFunction.

AWS SDK for .NET
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

/// <summary> /// Creates a new Lambda function. /// </summary> /// <param name="functionName">The name of the function.</param> /// <param name="s3Bucket">The Amazon Simple Storage Service (Amazon S3) /// bucket where the zip file containing the code is located.</param> /// <param name="s3Key">The Amazon S3 key of the zip file.</param> /// <param name="role">The Amazon Resource Name (ARN) of a role with the /// appropriate Lambda permissions.</param> /// <param name="handler">The name of the handler function.</param> /// <returns>The Amazon Resource Name (ARN) of the newly created /// Lambda function.</returns> public async Task<string> CreateLambdaFunctionAsync( string functionName, string s3Bucket, string s3Key, string role, string handler) { // Defines the location for the function code. // S3Bucket - The S3 bucket where the file containing // the source code is stored. // S3Key - The name of the file containing the code. var functionCode = new FunctionCode { S3Bucket = s3Bucket, S3Key = s3Key, }; var createFunctionRequest = new CreateFunctionRequest { FunctionName = functionName, Description = "Created by the Lambda .NET API", Code = functionCode, Handler = handler, Runtime = Runtime.Dotnet6, Role = role, }; var reponse = await _lambdaService.CreateFunctionAsync(createFunctionRequest); return reponse.FunctionArn; }
  • Para obtener más información sobre la API, consulta CreateFunctionla Referencia AWS SDK for .NET de la API.

En el siguiente ejemplo de código, se muestra cómo usar DeleteFunction.

AWS SDK for .NET
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

/// <summary> /// Delete an AWS Lambda function. /// </summary> /// <param name="functionName">The name of the Lambda function to /// delete.</param> /// <returns>A Boolean value that indicates the success of the action.</returns> public async Task<bool> DeleteFunctionAsync(string functionName) { var request = new DeleteFunctionRequest { FunctionName = functionName, }; var response = await _lambdaService.DeleteFunctionAsync(request); // A return value of NoContent means that the request was processed. // In this case, the function was deleted, and the return value // is intentionally blank. return response.HttpStatusCode == System.Net.HttpStatusCode.NoContent; }
  • Para obtener más información sobre la API, consulta DeleteFunctionla Referencia AWS SDK for .NET de la API.

En el siguiente ejemplo de código, se muestra cómo usar GetFunction.

AWS SDK for .NET
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

/// <summary> /// Gets information about a Lambda function. /// </summary> /// <param name="functionName">The name of the Lambda function for /// which to retrieve information.</param> /// <returns>Async Task.</returns> public async Task<FunctionConfiguration> GetFunctionAsync(string functionName) { var functionRequest = new GetFunctionRequest { FunctionName = functionName, }; var response = await _lambdaService.GetFunctionAsync(functionRequest); return response.Configuration; }
  • Para obtener más información sobre la API, consulta GetFunctionla Referencia AWS SDK for .NET de la API.

En el siguiente ejemplo de código, se muestra cómo usar Invoke.

AWS SDK for .NET
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

/// <summary> /// Invoke a Lambda function. /// </summary> /// <param name="functionName">The name of the Lambda function to /// invoke.</param /// <param name="parameters">The parameter values that will be passed to the function.</param> /// <returns>A System Threading Task.</returns> public async Task<string> InvokeFunctionAsync( string functionName, string parameters) { var payload = parameters; var request = new InvokeRequest { FunctionName = functionName, Payload = payload, }; var response = await _lambdaService.InvokeAsync(request); MemoryStream stream = response.Payload; string returnValue = System.Text.Encoding.UTF8.GetString(stream.ToArray()); return returnValue; }
  • Para obtener información sobre la API, consulte Invocar en la referencia de la API de AWS SDK for .NET .

En el siguiente ejemplo de código, se muestra cómo usar ListFunctions.

AWS SDK for .NET
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

/// <summary> /// Get a list of Lambda functions. /// </summary> /// <returns>A list of FunctionConfiguration objects.</returns> public async Task<List<FunctionConfiguration>> ListFunctionsAsync() { var functionList = new List<FunctionConfiguration>(); var functionPaginator = _lambdaService.Paginators.ListFunctions(new ListFunctionsRequest()); await foreach (var function in functionPaginator.Functions) { functionList.Add(function); } return functionList; }
  • Para obtener más información sobre la API, consulta ListFunctionsla Referencia AWS SDK for .NET de la API.

En el siguiente ejemplo de código, se muestra cómo usar UpdateFunctionCode.

AWS SDK for .NET
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

/// <summary> /// Update an existing Lambda function. /// </summary> /// <param name="functionName">The name of the Lambda function to update.</param> /// <param name="bucketName">The bucket where the zip file containing /// the Lambda function code is stored.</param> /// <param name="key">The key name of the source code file.</param> /// <returns>Async Task.</returns> public async Task UpdateFunctionCodeAsync( string functionName, string bucketName, string key) { var functionCodeRequest = new UpdateFunctionCodeRequest { FunctionName = functionName, Publish = true, S3Bucket = bucketName, S3Key = key, }; var response = await _lambdaService.UpdateFunctionCodeAsync(functionCodeRequest); Console.WriteLine($"The Function was last modified at {response.LastModified}."); }
  • Para obtener más información sobre la API, consulta UpdateFunctionCodela Referencia AWS SDK for .NET de la API.

En el siguiente ejemplo de código, se muestra cómo usar UpdateFunctionConfiguration.

AWS SDK for .NET
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

/// <summary> /// Update the code of a Lambda function. /// </summary> /// <param name="functionName">The name of the function to update.</param> /// <param name="functionHandler">The code that performs the function's actions.</param> /// <param name="environmentVariables">A dictionary of environment variables.</param> /// <returns>A Boolean value indicating the success of the action.</returns> public async Task<bool> UpdateFunctionConfigurationAsync( string functionName, string functionHandler, Dictionary<string, string> environmentVariables) { var request = new UpdateFunctionConfigurationRequest { Handler = functionHandler, FunctionName = functionName, Environment = new Amazon.Lambda.Model.Environment { Variables = environmentVariables }, }; var response = await _lambdaService.UpdateFunctionConfigurationAsync(request); Console.WriteLine(response.LastModified); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; }

Escenarios

En el siguiente ejemplo de código, se muestra cómo:

  • Crear un rol de IAM y una función de Lambda y, a continuación, cargar el código de controlador.

  • Invocar la función con un único parámetro y obtener resultados.

  • Actualizar el código de la función y configurar con una variable de entorno.

  • Invocar la función con un nuevo parámetro y obtener resultados. Mostrar el registro de ejecución devuelto.

  • Enumerar las funciones de su cuenta y, luego, limpiar los recursos.

Para obtener información, consulte Crear una función de Lambda con la consola.

AWS SDK for .NET
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

Cree métodos que realicen acciones de Lambda.

namespace LambdaActions; using Amazon.Lambda; using Amazon.Lambda.Model; /// <summary> /// A class that implements AWS Lambda methods. /// </summary> public class LambdaWrapper { private readonly IAmazonLambda _lambdaService; /// <summary> /// Constructor for the LambdaWrapper class. /// </summary> /// <param name="lambdaService">An initialized Lambda service client.</param> public LambdaWrapper(IAmazonLambda lambdaService) { _lambdaService = lambdaService; } /// <summary> /// Creates a new Lambda function. /// </summary> /// <param name="functionName">The name of the function.</param> /// <param name="s3Bucket">The Amazon Simple Storage Service (Amazon S3) /// bucket where the zip file containing the code is located.</param> /// <param name="s3Key">The Amazon S3 key of the zip file.</param> /// <param name="role">The Amazon Resource Name (ARN) of a role with the /// appropriate Lambda permissions.</param> /// <param name="handler">The name of the handler function.</param> /// <returns>The Amazon Resource Name (ARN) of the newly created /// Lambda function.</returns> public async Task<string> CreateLambdaFunctionAsync( string functionName, string s3Bucket, string s3Key, string role, string handler) { // Defines the location for the function code. // S3Bucket - The S3 bucket where the file containing // the source code is stored. // S3Key - The name of the file containing the code. var functionCode = new FunctionCode { S3Bucket = s3Bucket, S3Key = s3Key, }; var createFunctionRequest = new CreateFunctionRequest { FunctionName = functionName, Description = "Created by the Lambda .NET API", Code = functionCode, Handler = handler, Runtime = Runtime.Dotnet6, Role = role, }; var reponse = await _lambdaService.CreateFunctionAsync(createFunctionRequest); return reponse.FunctionArn; } /// <summary> /// Delete an AWS Lambda function. /// </summary> /// <param name="functionName">The name of the Lambda function to /// delete.</param> /// <returns>A Boolean value that indicates the success of the action.</returns> public async Task<bool> DeleteFunctionAsync(string functionName) { var request = new DeleteFunctionRequest { FunctionName = functionName, }; var response = await _lambdaService.DeleteFunctionAsync(request); // A return value of NoContent means that the request was processed. // In this case, the function was deleted, and the return value // is intentionally blank. return response.HttpStatusCode == System.Net.HttpStatusCode.NoContent; } /// <summary> /// Gets information about a Lambda function. /// </summary> /// <param name="functionName">The name of the Lambda function for /// which to retrieve information.</param> /// <returns>Async Task.</returns> public async Task<FunctionConfiguration> GetFunctionAsync(string functionName) { var functionRequest = new GetFunctionRequest { FunctionName = functionName, }; var response = await _lambdaService.GetFunctionAsync(functionRequest); return response.Configuration; } /// <summary> /// Invoke a Lambda function. /// </summary> /// <param name="functionName">The name of the Lambda function to /// invoke.</param /// <param name="parameters">The parameter values that will be passed to the function.</param> /// <returns>A System Threading Task.</returns> public async Task<string> InvokeFunctionAsync( string functionName, string parameters) { var payload = parameters; var request = new InvokeRequest { FunctionName = functionName, Payload = payload, }; var response = await _lambdaService.InvokeAsync(request); MemoryStream stream = response.Payload; string returnValue = System.Text.Encoding.UTF8.GetString(stream.ToArray()); return returnValue; } /// <summary> /// Get a list of Lambda functions. /// </summary> /// <returns>A list of FunctionConfiguration objects.</returns> public async Task<List<FunctionConfiguration>> ListFunctionsAsync() { var functionList = new List<FunctionConfiguration>(); var functionPaginator = _lambdaService.Paginators.ListFunctions(new ListFunctionsRequest()); await foreach (var function in functionPaginator.Functions) { functionList.Add(function); } return functionList; } /// <summary> /// Update an existing Lambda function. /// </summary> /// <param name="functionName">The name of the Lambda function to update.</param> /// <param name="bucketName">The bucket where the zip file containing /// the Lambda function code is stored.</param> /// <param name="key">The key name of the source code file.</param> /// <returns>Async Task.</returns> public async Task UpdateFunctionCodeAsync( string functionName, string bucketName, string key) { var functionCodeRequest = new UpdateFunctionCodeRequest { FunctionName = functionName, Publish = true, S3Bucket = bucketName, S3Key = key, }; var response = await _lambdaService.UpdateFunctionCodeAsync(functionCodeRequest); Console.WriteLine($"The Function was last modified at {response.LastModified}."); } /// <summary> /// Update the code of a Lambda function. /// </summary> /// <param name="functionName">The name of the function to update.</param> /// <param name="functionHandler">The code that performs the function's actions.</param> /// <param name="environmentVariables">A dictionary of environment variables.</param> /// <returns>A Boolean value indicating the success of the action.</returns> public async Task<bool> UpdateFunctionConfigurationAsync( string functionName, string functionHandler, Dictionary<string, string> environmentVariables) { var request = new UpdateFunctionConfigurationRequest { Handler = functionHandler, FunctionName = functionName, Environment = new Amazon.Lambda.Model.Environment { Variables = environmentVariables }, }; var response = await _lambdaService.UpdateFunctionConfigurationAsync(request); Console.WriteLine(response.LastModified); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; } }

Cree una función que ejecute el escenario.

global using System.Threading.Tasks; global using Amazon.IdentityManagement; global using Amazon.Lambda; global using LambdaActions; global using LambdaScenarioCommon; global using Microsoft.Extensions.DependencyInjection; global using Microsoft.Extensions.Hosting; global using Microsoft.Extensions.Logging; global using Microsoft.Extensions.Logging.Console; global using Microsoft.Extensions.Logging.Debug; using Amazon.Lambda.Model; using Microsoft.Extensions.Configuration; namespace LambdaBasics; public class LambdaBasics { private static ILogger logger = null!; static async Task Main(string[] args) { // Set up dependency injection for the Amazon service. using var host = Host.CreateDefaultBuilder(args) .ConfigureLogging(logging => logging.AddFilter("System", LogLevel.Debug) .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information) .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace)) .ConfigureServices((_, services) => services.AddAWSService<IAmazonLambda>() .AddAWSService<IAmazonIdentityManagementService>() .AddTransient<LambdaWrapper>() .AddTransient<LambdaRoleWrapper>() .AddTransient<UIWrapper>() ) .Build(); var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("settings.json") // Load test settings from .json file. .AddJsonFile("settings.local.json", true) // Optionally load local settings. .Build(); logger = LoggerFactory.Create(builder => { builder.AddConsole(); }) .CreateLogger<LambdaBasics>(); var lambdaWrapper = host.Services.GetRequiredService<LambdaWrapper>(); var lambdaRoleWrapper = host.Services.GetRequiredService<LambdaRoleWrapper>(); var uiWrapper = host.Services.GetRequiredService<UIWrapper>(); string functionName = configuration["FunctionName"]!; string roleName = configuration["RoleName"]!; string policyDocument = "{" + " \"Version\": \"2012-10-17\"," + " \"Statement\": [ " + " {" + " \"Effect\": \"Allow\"," + " \"Principal\": {" + " \"Service\": \"lambda.amazonaws.com\" " + " }," + " \"Action\": \"sts:AssumeRole\" " + " }" + "]" + "}"; var incrementHandler = configuration["IncrementHandler"]; var calculatorHandler = configuration["CalculatorHandler"]; var bucketName = configuration["BucketName"]; var incrementKey = configuration["IncrementKey"]; var calculatorKey = configuration["CalculatorKey"]; var policyArn = configuration["PolicyArn"]; uiWrapper.DisplayLambdaBasicsOverview(); // Create the policy to use with the AWS Lambda functions and then attach the // policy to a new role. var roleArn = await lambdaRoleWrapper.CreateLambdaRoleAsync(roleName, policyDocument); Console.WriteLine("Waiting for role to become active."); uiWrapper.WaitABit(15, "Wait until the role is active before trying to use it."); // Attach the appropriate AWS Identity and Access Management (IAM) role policy to the new role. var success = await lambdaRoleWrapper.AttachLambdaRolePolicyAsync(policyArn, roleName); uiWrapper.WaitABit(10, "Allow time for the IAM policy to be attached to the role."); // Create the Lambda function using a zip file stored in an Amazon Simple Storage Service // (Amazon S3) bucket. uiWrapper.DisplayTitle("Create Lambda Function"); Console.WriteLine($"Creating the AWS Lambda function: {functionName}."); var lambdaArn = await lambdaWrapper.CreateLambdaFunctionAsync( functionName, bucketName, incrementKey, roleArn, incrementHandler); Console.WriteLine("Waiting for the new function to be available."); Console.WriteLine($"The AWS Lambda ARN is {lambdaArn}"); // Get the Lambda function. Console.WriteLine($"Getting the {functionName} AWS Lambda function."); FunctionConfiguration config; do { config = await lambdaWrapper.GetFunctionAsync(functionName); Console.Write("."); } while (config.State != State.Active); Console.WriteLine($"\nThe function, {functionName} has been created."); Console.WriteLine($"The runtime of this Lambda function is {config.Runtime}."); uiWrapper.PressEnter(); // List the Lambda functions. uiWrapper.DisplayTitle("Listing all Lambda functions."); var functions = await lambdaWrapper.ListFunctionsAsync(); DisplayFunctionList(functions); uiWrapper.DisplayTitle("Invoke increment function"); Console.WriteLine("Now that it has been created, invoke the Lambda increment function."); string? value; do { Console.Write("Enter a value to increment: "); value = Console.ReadLine(); } while (string.IsNullOrEmpty(value)); string functionParameters = "{" + "\"action\": \"increment\", " + "\"x\": \"" + value + "\"" + "}"; var answer = await lambdaWrapper.InvokeFunctionAsync(functionName, functionParameters); Console.WriteLine($"{value} + 1 = {answer}."); uiWrapper.DisplayTitle("Update function"); Console.WriteLine("Now update the Lambda function code."); await lambdaWrapper.UpdateFunctionCodeAsync(functionName, bucketName, calculatorKey); do { config = await lambdaWrapper.GetFunctionAsync(functionName); Console.Write("."); } while (config.LastUpdateStatus == LastUpdateStatus.InProgress); await lambdaWrapper.UpdateFunctionConfigurationAsync( functionName, calculatorHandler, new Dictionary<string, string> { { "LOG_LEVEL", "DEBUG" } }); do { config = await lambdaWrapper.GetFunctionAsync(functionName); Console.Write("."); } while (config.LastUpdateStatus == LastUpdateStatus.InProgress); uiWrapper.DisplayTitle("Call updated function"); Console.WriteLine("Now call the updated function..."); bool done = false; do { string? opSelected; Console.WriteLine("Select the operation to perform:"); Console.WriteLine("\t1. add"); Console.WriteLine("\t2. subtract"); Console.WriteLine("\t3. multiply"); Console.WriteLine("\t4. divide"); Console.WriteLine("\tOr enter \"q\" to quit."); Console.WriteLine("Enter the number (1, 2, 3, 4, or q) of the operation you want to perform: "); do { Console.Write("Your choice? "); opSelected = Console.ReadLine(); } while (opSelected == string.Empty); var operation = (opSelected) switch { "1" => "add", "2" => "subtract", "3" => "multiply", "4" => "divide", "q" => "quit", _ => "add", }; if (operation == "quit") { done = true; } else { // Get two numbers and an action from the user. value = string.Empty; do { Console.Write("Enter the first value: "); value = Console.ReadLine(); } while (value == string.Empty); string? value2; do { Console.Write("Enter a second value: "); value2 = Console.ReadLine(); } while (value2 == string.Empty); functionParameters = "{" + "\"action\": \"" + operation + "\", " + "\"x\": \"" + value + "\"," + "\"y\": \"" + value2 + "\"" + "}"; answer = await lambdaWrapper.InvokeFunctionAsync(functionName, functionParameters); Console.WriteLine($"The answer when we {operation} the two numbers is: {answer}."); } uiWrapper.PressEnter(); } while (!done); // Delete the function created earlier. uiWrapper.DisplayTitle("Clean up resources"); // Detach the IAM policy from the IAM role. Console.WriteLine("First detach the IAM policy from the role."); success = await lambdaRoleWrapper.DetachLambdaRolePolicyAsync(policyArn, roleName); uiWrapper.WaitABit(15, "Let's wait for the policy to be fully detached from the role."); Console.WriteLine("Delete the AWS Lambda function."); success = await lambdaWrapper.DeleteFunctionAsync(functionName); if (success) { Console.WriteLine($"The {functionName} function was deleted."); } else { Console.WriteLine($"Could not remove the function {functionName}"); } // Now delete the IAM role created for use with the functions // created by the application. Console.WriteLine("Now we can delete the role that we created."); success = await lambdaRoleWrapper.DeleteLambdaRoleAsync(roleName); if (success) { Console.WriteLine("The role has been successfully removed."); } else { Console.WriteLine("Couldn't delete the role."); } Console.WriteLine("The Lambda Scenario is now complete."); uiWrapper.PressEnter(); // Displays a formatted list of existing functions returned by the // LambdaMethods.ListFunctions. void DisplayFunctionList(List<FunctionConfiguration> functions) { functions.ForEach(functionConfig => { Console.WriteLine($"{functionConfig.FunctionName}\t{functionConfig.Description}"); }); } } } namespace LambdaActions; using Amazon.IdentityManagement; using Amazon.IdentityManagement.Model; public class LambdaRoleWrapper { private readonly IAmazonIdentityManagementService _lambdaRoleService; public LambdaRoleWrapper(IAmazonIdentityManagementService lambdaRoleService) { _lambdaRoleService = lambdaRoleService; } /// <summary> /// Attach an AWS Identity and Access Management (IAM) role policy to the /// IAM role to be assumed by the AWS Lambda functions created for the scenario. /// </summary> /// <param name="policyArn">The Amazon Resource Name (ARN) of the IAM policy.</param> /// <param name="roleName">The name of the IAM role to attach the IAM policy to.</param> /// <returns>A Boolean value indicating the success of the action.</returns> public async Task<bool> AttachLambdaRolePolicyAsync(string policyArn, string roleName) { var response = await _lambdaRoleService.AttachRolePolicyAsync(new AttachRolePolicyRequest { PolicyArn = policyArn, RoleName = roleName }); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; } /// <summary> /// Create a new IAM role. /// </summary> /// <param name="roleName">The name of the IAM role to create.</param> /// <param name="policyDocument">The policy document for the new IAM role.</param> /// <returns>A string representing the ARN for newly created role.</returns> public async Task<string> CreateLambdaRoleAsync(string roleName, string policyDocument) { var request = new CreateRoleRequest { AssumeRolePolicyDocument = policyDocument, RoleName = roleName, }; var response = await _lambdaRoleService.CreateRoleAsync(request); return response.Role.Arn; } /// <summary> /// Deletes an IAM role. /// </summary> /// <param name="roleName">The name of the role to delete.</param> /// <returns>A Boolean value indicating the success of the operation.</returns> public async Task<bool> DeleteLambdaRoleAsync(string roleName) { var request = new DeleteRoleRequest { RoleName = roleName, }; var response = await _lambdaRoleService.DeleteRoleAsync(request); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; } public async Task<bool> DetachLambdaRolePolicyAsync(string policyArn, string roleName) { var response = await _lambdaRoleService.DetachRolePolicyAsync(new DetachRolePolicyRequest { PolicyArn = policyArn, RoleName = roleName }); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; } } namespace LambdaScenarioCommon; public class UIWrapper { public readonly string SepBar = new('-', Console.WindowWidth); /// <summary> /// Show information about the AWS Lambda Basics scenario. /// </summary> public void DisplayLambdaBasicsOverview() { Console.Clear(); DisplayTitle("Welcome to AWS Lambda Basics"); Console.WriteLine("This example application does the following:"); Console.WriteLine("\t1. Creates an AWS Identity and Access Management (IAM) role that will be assumed by the functions we create."); Console.WriteLine("\t2. Attaches an IAM role policy that has Lambda permissions."); Console.WriteLine("\t3. Creates a Lambda function that increments the value passed to it."); Console.WriteLine("\t4. Calls the increment function and passes a value."); Console.WriteLine("\t5. Updates the code so that the function is a simple calculator."); Console.WriteLine("\t6. Calls the calculator function with the values entered."); Console.WriteLine("\t7. Deletes the Lambda function."); Console.WriteLine("\t7. Detaches the IAM role policy."); Console.WriteLine("\t8. Deletes the IAM role."); PressEnter(); } /// <summary> /// Display a message and wait until the user presses enter. /// </summary> public void PressEnter() { Console.Write("\nPress <Enter> to continue. "); _ = Console.ReadLine(); Console.WriteLine(); } /// <summary> /// Pad a string with spaces to center it on the console display. /// </summary> /// <param name="strToCenter">The string to be centered.</param> /// <returns>The padded string.</returns> public string CenterString(string strToCenter) { var padAmount = (Console.WindowWidth - strToCenter.Length) / 2; var leftPad = new string(' ', padAmount); return $"{leftPad}{strToCenter}"; } /// <summary> /// Display a line of hyphens, the centered text of the title and another /// line of hyphens. /// </summary> /// <param name="strTitle">The string to be displayed.</param> public void DisplayTitle(string strTitle) { Console.WriteLine(SepBar); Console.WriteLine(CenterString(strTitle)); Console.WriteLine(SepBar); } /// <summary> /// Display a countdown and wait for a number of seconds. /// </summary> /// <param name="numSeconds">The number of seconds to wait.</param> public void WaitABit(int numSeconds, string msg) { Console.WriteLine(msg); // Wait for the requested number of seconds. for (int i = numSeconds; i > 0; i--) { System.Threading.Thread.Sleep(1000); Console.Write($"{i}..."); } PressEnter(); } }

Defina un controlador de Lambda que aumente un número.

using Amazon.Lambda.Core; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace LambdaIncrement; public class Function { /// <summary> /// A simple function increments the integer parameter. /// </summary> /// <param name="input">A JSON string containing an action, which must be /// "increment" and a string representing the value to increment.</param> /// <param name="context">The context object passed by Lambda containing /// information about invocation, function, and execution environment.</param> /// <returns>A string representing the incremented value of the parameter.</returns> public int FunctionHandler(Dictionary<string, string> input, ILambdaContext context) { if (input["action"] == "increment") { int inputValue = Convert.ToInt32(input["x"]); return inputValue + 1; } else { return 0; } } }

Defina un segundo controlador de Lambda que realice operaciones aritméticas.

using Amazon.Lambda.Core; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace LambdaCalculator; public class Function { /// <summary> /// A simple function that takes two number in string format and performs /// the requested arithmetic function. /// </summary> /// <param name="input">JSON data containing an action, and x and y values. /// Valid actions include: add, subtract, multiply, and divide.</param> /// <param name="context">The context object passed by Lambda containing /// information about invocation, function, and execution environment.</param> /// <returns>A string representing the results of the calculation.</returns> public int FunctionHandler(Dictionary<string, string> input, ILambdaContext context) { var action = input["action"]; int x = Convert.ToInt32(input["x"]); int y = Convert.ToInt32(input["y"]); int result; switch (action) { case "add": result = x + y; break; case "subtract": result = x - y; break; case "multiply": result = x * y; break; case "divide": if (y == 0) { Console.Error.WriteLine("Divide by zero error."); result = 0; } else result = x / y; break; default: Console.Error.WriteLine($"{action} is not a valid operation."); result = 0; break; } return result; } }

Ejemplos sin servidor

En el siguiente ejemplo de código se muestra cómo implementar una función de Lambda que recibe un evento activado al recibir registros de un flujo de Kinesis. La función recupera la carga útil de Kinesis, la decodifica desde Base64 y registra el contenido del registro.

AWS SDK for .NET
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el repositorio de ejemplos sin servidor.

Uso de un evento de Kinesis con Lambda mediante .NET.

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Text; using Amazon.Lambda.Core; using Amazon.Lambda.KinesisEvents; using AWS.Lambda.Powertools.Logging; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace KinesisIntegrationSampleCode; public class Function { // Powertools Logger requires an environment variables against your function // POWERTOOLS_SERVICE_NAME [Logging(LogEvent = true)] public async Task FunctionHandler(KinesisEvent evnt, ILambdaContext context) { if (evnt.Records.Count == 0) { Logger.LogInformation("Empty Kinesis Event received"); return; } foreach (var record in evnt.Records) { try { Logger.LogInformation($"Processed Event with EventId: {record.EventId}"); string data = await GetRecordDataAsync(record.Kinesis, context); Logger.LogInformation($"Data: {data}"); // TODO: Do interesting work based on the new data } catch (Exception ex) { Logger.LogError($"An error occurred {ex.Message}"); throw; } } Logger.LogInformation($"Successfully processed {evnt.Records.Count} records."); } private async Task<string> GetRecordDataAsync(KinesisEvent.Record record, ILambdaContext context) { byte[] bytes = record.Data.ToArray(); string data = Encoding.UTF8.GetString(bytes); await Task.CompletedTask; //Placeholder for actual async work return data; } }

El siguiente ejemplo de código muestra cómo implementar una función de Lambda que recibe un evento desencadenado al recibir registros de una transmisión de DynamoDB. La función recupera la carga útil de DynamoDB y registra el contenido del registro.

AWS SDK for .NET
nota

Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el repositorio de ejemplos sin servidor.

Consumo de un evento de DynamoDB con Lambda mediante .NET.

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Text.Json; using System.Text; using Amazon.Lambda.Core; using Amazon.Lambda.DynamoDBEvents; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace AWSLambda_DDB; public class Function { public void FunctionHandler(DynamoDBEvent dynamoEvent, ILambdaContext context) { context.Logger.LogInformation($"Beginning to process {dynamoEvent.Records.Count} records..."); foreach (var record in dynamoEvent.Records) { context.Logger.LogInformation($"Event ID: {record.EventID}"); context.Logger.LogInformation($"Event Name: {record.EventName}"); context.Logger.LogInformation(JsonSerializer.Serialize(record)); } context.Logger.LogInformation("Stream processing complete."); } }

En el siguiente ejemplo de código se muestra cómo implementar una función de Lambda que recibe un evento activado al cargar un objeto en un bucket de S3. La función recupera el nombre del bucket de S3 y la clave del objeto del parámetro de evento y llama a la API de Amazon S3 para recuperar y registrar el tipo de contenido del objeto.

AWS SDK for .NET
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el repositorio de ejemplos sin servidor.

Uso de un evento de S3 con Lambda mediante .NET.

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Threading.Tasks; using Amazon.Lambda.Core; using Amazon.S3; using System; using Amazon.Lambda.S3Events; using System.Web; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace S3Integration { public class Function { private static AmazonS3Client _s3Client; public Function() : this(null) { } internal Function(AmazonS3Client s3Client) { _s3Client = s3Client ?? new AmazonS3Client(); } public async Task<string> Handler(S3Event evt, ILambdaContext context) { try { if (evt.Records.Count <= 0) { context.Logger.LogLine("Empty S3 Event received"); return string.Empty; } var bucket = evt.Records[0].S3.Bucket.Name; var key = HttpUtility.UrlDecode(evt.Records[0].S3.Object.Key); context.Logger.LogLine($"Request is for {bucket} and {key}"); var objectResult = await _s3Client.GetObjectAsync(bucket, key); context.Logger.LogLine($"Returning {objectResult.Key}"); return objectResult.Key; } catch (Exception e) { context.Logger.LogLine($"Error processing request - {e.Message}"); return string.Empty; } } } }

En el siguiente ejemplo de código se muestra cómo implementar una función de Lambda que recibe un evento activado al recibir mensajes de un tema de SNS. La función recupera los mensajes del parámetro de eventos y registra el contenido de cada mensaje.

AWS SDK for .NET
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el repositorio de ejemplos sin servidor.

Uso de un evento de SNS con Lambda mediante .NET.

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using Amazon.Lambda.Core; using Amazon.Lambda.SNSEvents; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace SnsIntegration; public class Function { public async Task FunctionHandler(SNSEvent evnt, ILambdaContext context) { foreach (var record in evnt.Records) { await ProcessRecordAsync(record, context); } context.Logger.LogInformation("done"); } private async Task ProcessRecordAsync(SNSEvent.SNSRecord record, ILambdaContext context) { try { context.Logger.LogInformation($"Processed record {record.Sns.Message}"); // TODO: Do interesting work based on the new message await Task.CompletedTask; } catch (Exception e) { //You can use Dead Letter Queue to handle failures. By configuring a Lambda DLQ. context.Logger.LogError($"An error occurred"); throw; } } }

En el siguiente ejemplo de código se muestra cómo implementar una función de Lambda que recibe un evento activado al recibir mensajes de una cola de SQS. La función recupera los mensajes del parámetro de eventos y registra el contenido de cada mensaje.

AWS SDK for .NET
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el repositorio de ejemplos sin servidor.

Uso de un evento de SQS con Lambda mediante .NET.

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using Amazon.Lambda.Core; using Amazon.Lambda.SQSEvents; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace SqsIntegrationSampleCode { public async Task FunctionHandler(SQSEvent evnt, ILambdaContext context) { foreach (var message in evnt.Records) { await ProcessMessageAsync(message, context); } context.Logger.LogInformation("done"); } private async Task ProcessMessageAsync(SQSEvent.SQSMessage message, ILambdaContext context) { try { context.Logger.LogInformation($"Processed message {message.Body}"); // TODO: Do interesting work based on the new message await Task.CompletedTask; } catch (Exception e) { //You can use Dead Letter Queue to handle failures. By configuring a Lambda DLQ. context.Logger.LogError($"An error occurred"); throw; } } }

En el siguiente ejemplo de código se muestra cómo implementar una respuesta por lotes parcial para funciones de Lambda que reciben eventos de un flujo de Kinesis. La función informa los errores de los elementos del lote en la respuesta y le indica a Lambda que vuelva a intentar esos mensajes más adelante.

AWS SDK for .NET
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el repositorio de ejemplos sin servidor.

Notificación de los errores de los elementos del lote de Kinesis con Lambda mediante .NET.

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Text; using System.Text.Json.Serialization; using Amazon.Lambda.Core; using Amazon.Lambda.KinesisEvents; using AWS.Lambda.Powertools.Logging; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace KinesisIntegration; public class Function { // Powertools Logger requires an environment variables against your function // POWERTOOLS_SERVICE_NAME [Logging(LogEvent = true)] public async Task<StreamsEventResponse> FunctionHandler(KinesisEvent evnt, ILambdaContext context) { if (evnt.Records.Count == 0) { Logger.LogInformation("Empty Kinesis Event received"); return new StreamsEventResponse(); } foreach (var record in evnt.Records) { try { Logger.LogInformation($"Processed Event with EventId: {record.EventId}"); string data = await GetRecordDataAsync(record.Kinesis, context); Logger.LogInformation($"Data: {data}"); // TODO: Do interesting work based on the new data } catch (Exception ex) { Logger.LogError($"An error occurred {ex.Message}"); /* Since we are working with streams, we can return the failed item immediately. Lambda will immediately begin to retry processing from this failed item onwards. */ return new StreamsEventResponse { BatchItemFailures = new List<StreamsEventResponse.BatchItemFailure> { new StreamsEventResponse.BatchItemFailure { ItemIdentifier = record.Kinesis.SequenceNumber } } }; } } Logger.LogInformation($"Successfully processed {evnt.Records.Count} records."); return new StreamsEventResponse(); } private async Task<string> GetRecordDataAsync(KinesisEvent.Record record, ILambdaContext context) { byte[] bytes = record.Data.ToArray(); string data = Encoding.UTF8.GetString(bytes); await Task.CompletedTask; //Placeholder for actual async work return data; } } public class StreamsEventResponse { [JsonPropertyName("batchItemFailures")] public IList<BatchItemFailure> BatchItemFailures { get; set; } public class BatchItemFailure { [JsonPropertyName("itemIdentifier")] public string ItemIdentifier { get; set; } } }

El siguiente ejemplo de código muestra cómo implementar una respuesta por lotes parcial para las funciones de Lambda que reciben eventos de una transmisión de DynamoDB. La función informa los errores de los elementos del lote en la respuesta y le indica a Lambda que vuelva a intentar esos mensajes más adelante.

AWS SDK for .NET
nota

Hay más información al respecto. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el repositorio de ejemplos sin servidor.

Notificación de los errores de los elementos del lote de DynamoDB con Lambda mediante .NET.

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Text.Json; using System.Text; using Amazon.Lambda.Core; using Amazon.Lambda.DynamoDBEvents; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace AWSLambda_DDB; public class Function { public StreamsEventResponse FunctionHandler(DynamoDBEvent dynamoEvent, ILambdaContext context) { context.Logger.LogInformation($"Beginning to process {dynamoEvent.Records.Count} records..."); List<StreamsEventResponse.BatchItemFailure> batchItemFailures = new List<StreamsEventResponse.BatchItemFailure>(); StreamsEventResponse streamsEventResponse = new StreamsEventResponse(); foreach (var record in dynamoEvent.Records) { try { var sequenceNumber = record.Dynamodb.SequenceNumber; context.Logger.LogInformation(sequenceNumber); } catch (Exception ex) { context.Logger.LogError(ex.Message); batchItemFailures.Add(new StreamsEventResponse.BatchItemFailure() { ItemIdentifier = record.Dynamodb.SequenceNumber }); } } if (batchItemFailures.Count > 0) { streamsEventResponse.BatchItemFailures = batchItemFailures; } context.Logger.LogInformation("Stream processing complete."); return streamsEventResponse; } }

En el siguiente ejemplo de código se muestra cómo implementar una respuesta por lotes parcial para funciones de Lambda que reciben eventos de una cola de SQS. La función informa los errores de los elementos del lote en la respuesta y le indica a Lambda que vuelva a intentar esos mensajes más adelante.

AWS SDK for .NET
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el repositorio de ejemplos sin servidor.

Notificación de los errores de los elementos del lote de SQS con Lambda mediante .NET.

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using Amazon.Lambda.Core; using Amazon.Lambda.SQSEvents; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace sqsSample; public class Function { public async Task<SQSBatchResponse> FunctionHandler(SQSEvent evnt, ILambdaContext context) { List<SQSBatchResponse.BatchItemFailure> batchItemFailures = new List<SQSBatchResponse.BatchItemFailure>(); foreach(var message in evnt.Records) { try { //process your message await ProcessMessageAsync(message, context); } catch (System.Exception) { //Add failed message identifier to the batchItemFailures list batchItemFailures.Add(new SQSBatchResponse.BatchItemFailure{ItemIdentifier=message.MessageId}); } } return new SQSBatchResponse(batchItemFailures); } private async Task ProcessMessageAsync(SQSEvent.SQSMessage message, ILambdaContext context) { if (String.IsNullOrEmpty(message.Body)) { throw new Exception("No Body in SQS Message."); } context.Logger.LogInformation($"Processed message {message.Body}"); // TODO: Do interesting work based on the new message await Task.CompletedTask; } }