id
stringlengths
14
16
text
stringlengths
1
2.43k
source
stringlengths
99
229
891d60d703f0-0
Adds [tags](https://docs.aws.amazon.com/lambda/latest/dg/tagging.html) to a function\.
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/API_TagResource.md
0c395f7a43bd-0
``` POST /2017-03-31/tags/ARN HTTP/1.1 Content-type: application/json { "Tags": { "string" : "string" } } ```
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/API_TagResource.md
a56eb70ed663-0
The request uses the following URI parameters\. ** [ARN](#API_TagResource_RequestSyntax) ** <a name="SSS-TagResource-request-Resource"></a> The function's Amazon Resource Name \(ARN\)\. Pattern: `arn:(aws[a-zA-Z-]*)?:lambda:[a-z]{2}(-gov)?-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_]+(:(\$LATEST|[a-zA-Z0-9-_]+))?` Required: Yes
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/API_TagResource.md
9798e16353e9-0
The request accepts the following data in JSON format\. ** [Tags](#API_TagResource_RequestSyntax) ** <a name="SSS-TagResource-request-Tags"></a> A list of tags to apply to the function\. Type: String to string map Required: Yes
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/API_TagResource.md
c3610c31457c-0
``` HTTP/1.1 204 ```
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/API_TagResource.md
1dab14b24974-0
If the action is successful, the service sends back an HTTP 204 response with an empty HTTP body\.
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/API_TagResource.md
97a1028d0e98-0
**InvalidParameterValueException** One of the parameters in the request is invalid\. HTTP Status Code: 400 **ResourceConflictException** The resource already exists, or another operation is in progress\. HTTP Status Code: 409 **ResourceNotFoundException** The resource specified in the request does not exist\. HTTP Status Code: 404 **ServiceException** The AWS Lambda service encountered an internal error\. HTTP Status Code: 500 **TooManyRequestsException** The request throughput limit was exceeded\. HTTP Status Code: 429
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/API_TagResource.md
1d366c3230dd-0
For more information about using this API in one of the language\-specific AWS SDKs, see the following: + [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/TagResource) + [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/TagResource) + [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/TagResource) + [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/TagResource) + [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/TagResource) + [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/TagResource) + [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/TagResource)
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/API_TagResource.md
1d366c3230dd-1
+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/TagResource) + [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/TagResource)
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/API_TagResource.md
38b8ecd2727f-0
When a Lambda function is invoked, the Lambda handler invokes the PowerShell script\. When the PowerShell script is invoked, the following variables are predefined: + *$LambdaInput* – A PSObject that contains the input to the handler\. This input can be event data \(published by an event source\) or custom input that you provide, such as a string or any custom data object\. + *$LambdaContext* – An Amazon\.Lambda\.Core\.ILambdaContext object that you can use to access information about the current execution—such as the name of the current function, the memory limit, execution time remaining, and logging\. For example, consider the following PowerShell example code\. ``` #Requires -Modules @{ModuleName='AWSPowerShell.NetCore';ModuleVersion='3.3.618.0'} Write-Host 'Function Name:' $LambdaContext.FunctionName ``` This script returns the FunctionName property that's obtained from the $LambdaContext variable\. **Note**
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/powershell-handler.md
38b8ecd2727f-1
``` This script returns the FunctionName property that's obtained from the $LambdaContext variable\. **Note** You're required to use the `#Requires` statement within your PowerShell scripts to indicate the modules that your scripts depend on\. This statement performs two important tasks\. 1\) It communicates to other developers which modules the script uses, and 2\) it identifies the dependent modules that AWS PowerShell tools need to package with the script, as part of the deployment\. For more information about the `#Requires` statement in PowerShell, see [ About requires](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_requires?view=powershell-6)\. For more information about PowerShell deployment packages, see [AWS Lambda deployment package in PowerShell](powershell-package.md)\. When your PowerShell Lambda function uses the AWS PowerShell cmdlets, be sure to set a `#Requires` statement that references the `AWSPowerShell.NetCore` module, which supports PowerShell Core—and not the `AWSPowerShell` module, which only supports Windows PowerShell\. Also, be sure to use version 3\.3\.270\.0 or newer of `AWSPowerShell.NetCore` which optimizes the cmdlet import process\. If you use an older version, you'll experience longer cold starts\. For more information, see [ AWS Tools for PowerShell](https://aws.amazon.com/documentation/powershell/?id=docs_gateway)\.
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/powershell-handler.md
44af52a54fd8-0
Some Lambda invocations are meant to return data back to their caller\. For example, if an invocation was in response to a web request coming from API Gateway, then our Lambda function needs to return back the response\. For PowerShell Lambda, the last object that's added to the PowerShell pipeline is the return data from the Lambda invocation\. If the object is a string, the data is returned as is\. Otherwise the object is converted to JSON by using the `ConvertTo-Json` cmdlet\. For example, consider the following PowerShell statement, which adds `$PSVersionTable` to the PowerShell pipeline: ``` $PSVersionTable ``` After the PowerShell script is finished, the last object in the PowerShell pipeline is the return data for the Lambda function\. `$PSVersionTable` is a PowerShell global variable that also provides information about the running environment\.
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/powershell-handler.md
bc701fa0bae8-0
AWS IoT provides secure communication between internet\-connected devices \(such as sensors\) and the AWS Cloud\. This makes it possible for you to collect, store, and analyze telemetry data from multiple devices\. You can create AWS IoT rules for your devices to interact with AWS services\. The AWS IoT [Rules Engine](https://docs.aws.amazon.com/iot/latest/developerguide/iot-rules.html) provides a SQL\-based language to select data from message payloads and send the data to other services, such as Amazon S3, Amazon DynamoDB, and AWS Lambda\. You define a rule to invoke a Lambda function when you want to invoke another AWS service or a third\-party service\. When an incoming IoT message triggers the rule, AWS IoT invokes your Lambda function [asynchronously](invocation-async.md) and passes data from the IoT message to the function\. The following example shows a moisture reading from a greenhouse sensor\. The **row** and **pos** values identify the location of the sensor\. This example event is based on the greenhouse type in the [AWS IoT Rules tutorials](https://docs.aws.amazon.com/iot/latest/developerguide/iot-rules-tutorial.html)\. **Example AWS IoT message event** ``` { "row" : "10", "pos" : "23", "moisture" : "75" }
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/services-iot.md
bc701fa0bae8-1
"row" : "10", "pos" : "23", "moisture" : "75" } ``` For asynchronous invocation, Lambda queues the message and [retries](invocation-retries.md) if your function returns an error\. Configure your function with a [destination](invocation-async.md#invocation-async-destinations) to retain events that your function could not process\. You need to grant permission for the AWS IoT service to invoke your Lambda function\. Use the `add-permission` command to add a permission statement to your function's resource\-based policy\. ``` $ aws lambda add-permission --function-name my-function \ --statement-id iot-events --action "lambda:InvokeFunction" --principal iotevents.amazonaws.com { "Statement": "{\"Sid\":\"iot-events\",\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"iot.amazonaws.com\"},\"Action\":\"lambda:InvokeFunction\",\"Resource\":\"arn:aws:lambda:us-west-2:123456789012:function:my-function\"}" } ```
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/services-iot.md
bc701fa0bae8-2
} ``` For more information about how to use Lambda with AWS IoT, see [Creating an AWS Lambda rule](https://docs.aws.amazon.com/iot/latest/developerguide/iot-lambda-rule.html)\.
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/services-iot.md
7eb64dfa3a61-0
When you invoke a Lambda function, Lambda validates the request and checks for scaling capacity before sending the event to your function or, for asynchronous invocation, to the event queue\. Invocation errors can be caused by issues with request parameters, event structure, function settings, user permissions, resource permissions, or limits\. If you invoke your function directly, you see invocation errors in the response from Lambda\. If you invoke your function asynchronously with an event source mapping or through another service, you might find errors in logs, a dead\-letter queue, or a failed\-event destination\. Error handling options and retry behavior vary depending on how you invoke your function and on the type of error\. For a list of error types that can be returned by the `Invoke` operation, see [Invoke](API_Invoke.md)\. **Error:** *User: arn:aws:iam::123456789012:user/developer is not authorized to perform: lambda:InvokeFunction on resource: my\-function* Your IAM user, or the role that you assume, needs permission to invoke a function\. This requirement also applies to Lambda functions and other compute resources that invoke functions\. Add the **AWSLambdaRole** managed policy, or a custom policy that allows the `lambda:InvokeFunction` action on the target function, to your IAM user\. **Note**
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/troubleshooting-invocation.md
7eb64dfa3a61-1
**Note** Unlike other API actions in Lambda, the name of the action in IAM \(`lambda:InvokeFunction`\) doesn't match the name of the API action \(`Invoke`\) for invoking a function\. For more information, see [AWS Lambda permissions](lambda-permissions.md)\. **Error:** *ResourceConflictException: The operation cannot be performed at this time\. The function is currently in the following state: Pending* When you connect a function to a VPC at the time of creation, the function enters a `Pending` state while Lambda creates elastic network interfaces\. During this time, you can't invoke or modify your function\. If you connect your function to a VPC after creation, you can invoke it while the update is pending, but you can't modify its code or configuration\. For more information, see [Monitoring the state of a function with the Lambda API](functions-states.md)\. **Error:** *A function is stuck in the `Pending` state for several minutes\.* If a function becomes stuck in the `Pending` state for more than six minutes, call one of the following API operations to unblock it\. + [UpdateFunctionCode](API_UpdateFunctionCode.md) + [UpdateFunctionConfiguration](API_UpdateFunctionConfiguration.md) + [PublishVersion](API_PublishVersion.md)
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/troubleshooting-invocation.md
7eb64dfa3a61-2
+ [PublishVersion](API_PublishVersion.md) Lambda cancels the pending operation and puts the function into the `Failed` state\. You can then delete the function and recreate it, or attempt another update\. **Issue:** *One function is using all of the available concurrency, causing other functions to be throttled\.* To divide the available concurrency in a Region into pools, use [reserved concurrency](configuration-concurrency.md)\. Reserved concurrency ensures that a function can always scale to its assigned concurrency, and also that it won't scale beyond its assigned concurrency\. **Issue:** *You can invoke your function directly, but it doesn't run when another service or account invokes it\.* You grant [other services](lambda-services.md) and accounts permission to invoke a function in the function's [resource\-based policy](access-control-resource-based.md)\. If the invoker is in another account, that user also needs [permission to invoke functions](access-control-identity-based.md)\. **Issue:** *Function is invoked continuously in a loop\.*
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/troubleshooting-invocation.md
7eb64dfa3a61-3
**Issue:** *Function is invoked continuously in a loop\.* This typically occurs when your function manages resources in the same AWS service that triggers it\. For example, it is possible to create a function that stores an object in an Amazon S3 bucket that is configured with a [notification that invokes the function again](with-s3.md)\. To stop the function from running, choose **Throttle** on the [function configuration page](configuration-console.md)\. Then identify the code path or configuration error that caused the recursive invocation\. **Error:** *KMSDisabledException: Lambda was unable to decrypt the environment variables because the KMS key used is disabled\. Please check the function's KMS key settings\.* This error can occur if your KMS key is disabled, or if the grant that allows Lambda to use the key is revoked\. If the grant is missing, configure the function to use a different key\. Then reassign the custom key to recreate the grant\. **Error:** *EFSMountFailureException: The function could not mount the EFS file system with access point arn:aws:elasticfilesystem:us\-east\-2:123456789012:access\-point/fsap\-015cxmplb72b405fd\.* The mount request to the function's [file system](configuration-filesystem.md) was rejected\. Check the function's permissions, and confirm that its file system and access point exist and are ready for use\.
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/troubleshooting-invocation.md
7eb64dfa3a61-4
**Error:** *EFSMountConnectivityException: The function couldn't connect to the Amazon EFS file system with access point arn:aws:elasticfilesystem:us\-east\-2:123456789012:access\-point/fsap\-015cxmplb72b405fd\. Check your network configuration and try again\.* The function couldn't establish a connection to the function's [file system](configuration-filesystem.md) with the NFS protocol \(TCP port 2049\)\. Check the [security group and routing configuration](https://docs.aws.amazon.com/efs/latest/ug/network-access.html) for the VPC's subnets\. **Error:** *EFSMountTimeoutException: The function could not mount the EFS file system with access point \{arn:aws:elasticfilesystem:us\-east\-2:123456789012:access\-point/fsap\-015cxmplb72b405fd\} due to mount time out* The function was able to connect to the function's [file system](configuration-filesystem.md), but the mount operation timed out\. Try again after a short time and consider limiting the function's [concurrency](configuration-concurrency.md) to reduce load on the file system\. **Error:** *EFSIOException: This function instance was stopped because Lambda detected an IO process that was taking too long\.*
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/troubleshooting-invocation.md
7eb64dfa3a61-5
**Error:** *EFSIOException: This function instance was stopped because Lambda detected an IO process that was taking too long\.* A previous invocation timed out and Lambda was unable to terminate the function handler\. This issue can occur when an attached file system runs out of burst credits and the baseline throughput is insufficient\. To increase throughput, you can increase the size of the file system or use provisioned throughput\. For more information, see [Throughput](services-efs.md#services-efs-throughput)\.
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/troubleshooting-invocation.md
8ad0cb6dbac4-0
Lists event source mappings\. Specify an `EventSourceArn` to only show event source mappings for a single event source\.
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/API_ListEventSourceMappings.md
c15e9fc4ef55-0
``` GET /2015-03-31/event-source-mappings/?EventSourceArn=EventSourceArn&FunctionName=FunctionName&Marker=Marker&MaxItems=MaxItems HTTP/1.1 ```
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/API_ListEventSourceMappings.md
6c04e7c6187a-0
The request uses the following URI parameters\. ** [EventSourceArn](#API_ListEventSourceMappings_RequestSyntax) ** <a name="SSS-ListEventSourceMappings-request-EventSourceArn"></a> The Amazon Resource Name \(ARN\) of the event source\. + **Amazon Kinesis** \- The ARN of the data stream or a stream consumer\. + **Amazon DynamoDB Streams** \- The ARN of the stream\. + **Amazon Simple Queue Service** \- The ARN of the queue\. + **Amazon Managed Streaming for Apache Kafka** \- The ARN of the cluster\. Pattern: `arn:(aws[a-zA-Z0-9-]*):([a-zA-Z0-9\-])+:([a-z]{2}(-gov)?-[a-z]+-\d{1})?:(\d{12})?:(.*)` ** [FunctionName](#API_ListEventSourceMappings_RequestSyntax) ** <a name="SSS-ListEventSourceMappings-request-FunctionName"></a> The name of the Lambda function\. **Name formats** + **Function name** \- `MyFunction`\.
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/API_ListEventSourceMappings.md
6c04e7c6187a-1
The name of the Lambda function\. **Name formats** + **Function name** \- `MyFunction`\. + **Function ARN** \- `arn:aws:lambda:us-west-2:123456789012:function:MyFunction`\. + **Version or Alias ARN** \- `arn:aws:lambda:us-west-2:123456789012:function:MyFunction:PROD`\. + **Partial ARN** \- `123456789012:function:MyFunction`\. The length constraint applies only to the full ARN\. If you specify only the function name, it's limited to 64 characters in length\. Length Constraints: Minimum length of 1\. Maximum length of 140\. Pattern: `(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?` ** [Marker](#API_ListEventSourceMappings_RequestSyntax) ** <a name="SSS-ListEventSourceMappings-request-Marker"></a>
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/API_ListEventSourceMappings.md
6c04e7c6187a-2
A pagination token returned by a previous call\. ** [MaxItems](#API_ListEventSourceMappings_RequestSyntax) ** <a name="SSS-ListEventSourceMappings-request-MaxItems"></a> The maximum number of event source mappings to return\. Valid Range: Minimum value of 1\. Maximum value of 10000\.
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/API_ListEventSourceMappings.md
715f959b20b8-0
The request does not have a request body\.
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/API_ListEventSourceMappings.md
3d2539e3c7d1-0
``` HTTP/1.1 200 Content-type: application/json { "EventSourceMappings": [ { "BatchSize": number, "BisectBatchOnFunctionError": boolean, "DestinationConfig": { "OnFailure": { "Destination": "string" }, "OnSuccess": { "Destination": "string" } }, "EventSourceArn": "string", "FunctionArn": "string", "LastModified": number, "LastProcessingResult": "string", "MaximumBatchingWindowInSeconds": number, "MaximumRecordAgeInSeconds": number, "MaximumRetryAttempts": number, "ParallelizationFactor": number, "State": "string", "StateTransitionReason": "string", "Topics": [ "string" ], "UUID": "string" } ], "NextMarker": "string" } ```
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/API_ListEventSourceMappings.md
4b9f7ba12d4a-0
If the action is successful, the service sends back an HTTP 200 response\. The following data is returned in JSON format by the service\. ** [EventSourceMappings](#API_ListEventSourceMappings_ResponseSyntax) ** <a name="SSS-ListEventSourceMappings-response-EventSourceMappings"></a> A list of event source mappings\. Type: Array of [EventSourceMappingConfiguration](API_EventSourceMappingConfiguration.md) objects ** [NextMarker](#API_ListEventSourceMappings_ResponseSyntax) ** <a name="SSS-ListEventSourceMappings-response-NextMarker"></a> A pagination token that's returned when the response doesn't contain all event source mappings\. Type: String
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/API_ListEventSourceMappings.md
0ac9b5cf1f2f-0
**InvalidParameterValueException** One of the parameters in the request is invalid\. HTTP Status Code: 400 **ResourceNotFoundException** The resource specified in the request does not exist\. HTTP Status Code: 404 **ServiceException** The AWS Lambda service encountered an internal error\. HTTP Status Code: 500 **TooManyRequestsException** The request throughput limit was exceeded\. HTTP Status Code: 429
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/API_ListEventSourceMappings.md
37aa93bfd960-0
For more information about using this API in one of the language\-specific AWS SDKs, see the following: + [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/ListEventSourceMappings) + [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/ListEventSourceMappings) + [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/ListEventSourceMappings) + [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/ListEventSourceMappings) + [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/ListEventSourceMappings) + [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/ListEventSourceMappings)
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/API_ListEventSourceMappings.md
37aa93bfd960-1
+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/ListEventSourceMappings) + [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/ListEventSourceMappings) + [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/ListEventSourceMappings)
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/API_ListEventSourceMappings.md
68a86c848b1b-0
Suppose you want to create a thumbnail for each image file that is uploaded to a bucket\. You can create a Lambda function \(`CreateThumbnail`\) that Amazon S3 can invoke when objects are created\. Then, the Lambda function can read the image object from the source bucket and create a thumbnail image target bucket\. Upon completing this tutorial, you will have the following Amazon S3, Lambda, and IAM resources in your account: ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/s3-admin-iser-walkthrough-10.png) **Lambda resources** + A Lambda function\. + An access policy associated with your Lambda function that grants Amazon S3 permission to invoke the Lambda function\. **IAM resources** + An execution role that grants permissions that your Lambda function needs through the permissions policy associated with this role\. **Amazon S3 resources** + A source bucket with a notification configuration that invokes the Lambda function\. + A target bucket where the function saves resized images\.
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/with-s3-example.md
17bf4ac0c707-0
This tutorial assumes that you have some knowledge of basic Lambda operations and the Lambda console\. If you haven't already, follow the instructions in [Getting started with AWS Lambda](getting-started.md) to create your first Lambda function\. To follow the procedures in this guide, you will need a command line terminal or shell to run commands\. Commands are shown in listings preceded by a prompt symbol \($\) and the name of the current directory, when appropriate: ``` ~/lambda-project$ this is a command this is output ``` For long commands, an escape character \(`\`\) is used to split a command over multiple lines\. On Linux and macOS, use your preferred shell and package manager\. On Windows 10, you can [install the Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to get a Windows\-integrated version of Ubuntu and Bash\. Install npm to manage the function's dependencies\. The tutorial uses AWS CLI commands to create and invoke the Lambda function\. Install the [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html) and [configure it with your AWS credentials](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/with-s3-example.md
4357ad357b70-0
Create the [execution role](lambda-intro-execution-role.md) that gives your function permission to access AWS resources\. **To create an execution role** 1. Open the [roles page](https://console.aws.amazon.com/iam/home#/roles) in the IAM console\. 1. Choose **Create role**\. 1. Create a role with the following properties\. + **Trusted entity** – **AWS Lambda**\. + **Permissions** – **AWSLambdaExecute**\. + **Role name** – **lambda\-s3\-role**\. The **AWSLambdaExecute** policy has the permissions that the function needs to manage objects in Amazon S3 and write logs to CloudWatch Logs\.
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/with-s3-example.md
3582ea6f7b1d-0
Follow the steps to create buckets and upload an object\. 1. Open the [Amazon S3 console](https://console.aws.amazon.com/s3)\. 1. Create two buckets\. The target bucket name must be *source* followed by **\-resized**, where *source* is the name of the bucket you want to use for the source\. For example, `mybucket` and `mybucket-resized`\. 1. In the source bucket, upload a \.jpg object, `HappyFace.jpg`\. When you invoke the Lambda function manually before you connect to Amazon S3, you pass sample event data to the function that specifies the source bucket and `HappyFace.jpg` as the newly created object so you need to create this sample object first\.
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/with-s3-example.md
1c8987c935c5-0
The following example code receives an Amazon S3 event input and processes the message that it contains\. It resizes an image in the source bucket and saves the output to the target bucket\. **Note** For sample code in other languages, see [Sample Amazon S3 function code](with-s3-example-deployment-pkg.md)\. **Example index\.js** ``` // dependencies const AWS = require('aws-sdk'); const util = require('util'); const sharp = require('sharp'); // get reference to S3 client const s3 = new AWS.S3(); exports.handler = async (event, context, callback) => { // Read options from the event parameter. console.log("Reading options from event:\n", util.inspect(event, {depth: 5})); const srcBucket = event.Records[0].s3.bucket.name; // Object key may have spaces or unicode non-ASCII characters. const srcKey = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, " ")); const dstBucket = srcBucket + "-resized"; const dstKey = "resized-" + srcKey;
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/with-s3-example.md
1c8987c935c5-1
const dstBucket = srcBucket + "-resized"; const dstKey = "resized-" + srcKey; // Infer the image type from the file suffix. const typeMatch = srcKey.match(/\.([^.]*)$/); if (!typeMatch) { console.log("Could not determine the image type."); return; } // Check that the image type is supported const imageType = typeMatch[1].toLowerCase(); if (imageType != "jpg" && imageType != "png") { console.log(`Unsupported image type: ${imageType}`); return; } // Download the image from the S3 source bucket. try { const params = { Bucket: srcBucket, Key: srcKey }; var origimage = await s3.getObject(params).promise(); } catch (error) { console.log(error); return; } // set thumbnail width. Resize will set the height automatically to maintain aspect ratio. const width = 200; // Use the Sharp module to resize the image and save in a buffer. try {
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/with-s3-example.md
1c8987c935c5-2
const width = 200; // Use the Sharp module to resize the image and save in a buffer. try { var buffer = await sharp(origimage.Body).resize(width).toBuffer(); } catch (error) { console.log(error); return; } // Upload the thumbnail image to the destination bucket try { const destparams = { Bucket: dstBucket, Key: dstKey, Body: buffer, ContentType: "image" }; const putResult = await s3.putObject(destparams).promise(); } catch (error) { console.log(error); return; } console.log('Successfully resized ' + srcBucket + '/' + srcKey + ' and uploaded to ' + dstBucket + '/' + dstKey); }; ``` Review the preceding code and note the following: + The function knows the source bucket name and the key name of the object from the event data it receives as parameters\. If the object is a \.jpg or a \.png, the code creates a thumbnail and saves it to the target bucket\.
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/with-s3-example.md
1c8987c935c5-3
+ The code assumes that the destination bucket exists and its name is a concatenation of the source bucket name followed by the string `-resized`\. For example, if the source bucket identified in the event data is `examplebucket`, the code assumes you have an `examplebucket-resized` destination bucket\. + For the thumbnail it creates, the code derives its key name as the concatenation of the string `resized-` followed by the source object key name\. For example, if the source object key is `sample.jpg`, the code creates a thumbnail object that has the key `resized-sample.jpg`\. The deployment package is a \.zip file containing your Lambda function code and dependencies\. **To create a deployment package** 1. Open a command line terminal or shell in a Linux environment\. Ensure that the Node\.js version in your local environment matches the Node\.js version of your function\. 1. Save the function code as `index.js` in a folder named `lambda-s3`\. 1. Install the Sharp library with npm\. For Linux, use the following command\. ``` lambda-s3$ npm install sharp ``` For macOS, use the following command\. ``` lambda-s3$ npm install --arch=x64 --platform=linux --target=12.13.0 sharp ``` After you complete this step, you will have the following folder structure: ```
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/with-s3-example.md
1c8987c935c5-4
``` After you complete this step, you will have the following folder structure: ``` lambda-s3 |- index.js |- /node_modules/sharp └ /node_modules/... ``` 1. Create a deployment package with the function code and dependencies\. ``` lambda-s3$ zip -r function.zip . ``` **To create the function** + Create a Lambda function with the `create-function` command\. ``` $ aws lambda create-function --function-name CreateThumbnail \ --zip-file fileb://function.zip --handler index.handler --runtime nodejs12.x \ --timeout 10 --memory-size 1024 \ --role arn:aws:iam::123456789012:role/lambda-s3-role ``` For the role parameter, replace the number sequence with your AWS account ID\. The preceding example command specifies a 10\-second timeout value as the function configuration\. Depending on the size of objects you upload, you might need to increase the timeout value using the following AWS CLI command\. ``` $ aws lambda update-function-configuration --function-name CreateThumbnail --timeout 30 ```
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/with-s3-example.md
d33e1c14549c-0
In this step, you invoke the Lambda function manually using sample Amazon S3 event data\. **To test the Lambda function** 1. Save the following Amazon S3 sample event data in a file and save it as `inputFile.txt`\. You need to update the JSON by providing your *sourcebucket* name and a \.jpg object key\. ``` { "Records":[ { "eventVersion":"2.0", "eventSource":"aws:s3", "awsRegion":"us-west-2", "eventTime":"1970-01-01T00:00:00.000Z", "eventName":"ObjectCreated:Put", "userIdentity":{ "principalId":"AIDAJDPLRKLG7UEXAMPLE" }, "requestParameters":{ "sourceIPAddress":"127.0.0.1" }, "responseElements":{ "x-amz-request-id":"C3D13FE58DE4C810", "x-amz-id-2":"FMyUVURIY8/IgAtTv8xRjskZQpcIZ9KG4V5Wp6S7S/JRWeUWerMUE5JgHvANOjpD" },
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/with-s3-example.md
d33e1c14549c-1
}, "s3":{ "s3SchemaVersion":"1.0", "configurationId":"testConfigRule", "bucket":{ "name":"sourcebucket", "ownerIdentity":{ "principalId":"A3NL1KOZZKExample" }, "arn":"arn:aws:s3:::sourcebucket" }, "object":{ "key":"HappyFace.jpg", "size":1024, "eTag":"d41d8cd98f00b204e9800998ecf8427e", "versionId":"096fKKXTRTtl3on89fVO.nfljtsv6qko" } } } ] } ``` 1. Run the following Lambda CLI `invoke` command to invoke the function\. Note that the command requests asynchronous execution\. You can optionally invoke it synchronously by specifying `RequestResponse` as the `invocation-type` parameter value\. ``` $ aws lambda invoke --function-name CreateThumbnail --invocation-type Event \
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/with-s3-example.md
d33e1c14549c-2
``` $ aws lambda invoke --function-name CreateThumbnail --invocation-type Event \ --payload file://inputFile.txt outputfile.txt ``` 1. Verify that the thumbnail was created in the target bucket\.
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/with-s3-example.md
7a90f073db59-0
In this step, you add the remaining configuration so that Amazon S3 can publish object\-created events to AWS Lambda and invoke your Lambda function\. You do the following in this step: + Add permissions to the Lambda function access policy to allow Amazon S3 to invoke the function\. + Add notification configuration to your source bucket\. In the notification configuration, you provide the following: + Event type for which you want Amazon S3 to publish events\. For this tutorial, you specify the `s3:ObjectCreated:*` event type so that Amazon S3 publishes events when objects are created\. + Lambda function to invoke\. **To add permissions to the function policy** 1. Run the following Lambda CLI `add-permission` command to grant Amazon S3 service principal \(`s3.amazonaws.com`\) permissions to perform the `lambda:InvokeFunction` action\. Note that permission is granted to Amazon S3 to invoke the function only if the following conditions are met: + An object\-created event is detected on a specific bucket\. + The bucket is owned by your account\. If you delete a bucket, it is possible for another account to create a bucket with the same ARN\. ``` $ aws lambda add-permission --function-name CreateThumbnail --principal s3.amazonaws.com \ --statement-id s3invoke --action "lambda:InvokeFunction" \
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/with-s3-example.md
7a90f073db59-1
--statement-id s3invoke --action "lambda:InvokeFunction" \ --source-arn arn:aws:s3:::sourcebucket \ --source-account account-id ``` 1. Verify the function's access policy by running the AWS CLI `get-policy` command\. ``` $ aws lambda get-policy --function-name CreateThumbnail ``` Add notification configuration on the source bucket to request Amazon S3 to publish object\-created events to Lambda\. **Important** This procedure configures the bucket to invoke your function every time an object is created in it\. Ensure that you configure this option only on the source bucket and do not create objects in the source bucket from the function that is triggered\. Otherwise, your function could cause itself to be [invoked continuously in a loop](with-s3.md#services-s3-runaway)\. **To configure notifications** 1. Open the [Amazon S3 console](https://console.aws.amazon.com/s3)\. 1. Choose the source bucket\. 1. Choose **Properties**\. 1. Under **Events**, configure a notification with the following settings\. + **Name** – **lambda\-trigger**\. + **Events** – **All object create events**\.
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/with-s3-example.md
7a90f073db59-2
+ **Name** – **lambda\-trigger**\. + **Events** – **All object create events**\. + **Send to** – **Lambda function**\. + **Lambda** – **CreateThumbnail**\. For more information on event configuration, see [Enabling event notifications](https://docs.aws.amazon.com/AmazonS3/latest/user-guide/enable-event-notifications.html) in the *Amazon Simple Storage Service Console User Guide*\.
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/with-s3-example.md
cead529fe92a-0
Now you can test the setup as follows: 1. Upload \.jpg or \.png objects to the source bucket using the Amazon S3 console\. 1. Verify that the thumbnail was created in the target bucket using the `CreateThumbnail` function\. 1. View logs in the CloudWatch console\.
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/with-s3-example.md
52dd8d6bbf36-0
You can now delete the resources that you created for this tutorial, unless you want to retain them\. By deleting AWS resources that you are no longer using, you prevent unnecessary charges to your AWS account\. **To delete the Lambda function** 1. Open the [Functions page](https://console.aws.amazon.com/lambda/home#/functions) of the Lambda console\. 1. Select the function that you created\. 1. Choose **Actions**, **Delete**\. 1. Choose **Delete**\. **To delete the execution role** 1. Open the [Roles page](https://console.aws.amazon.com/iam/home#/roles) of the IAM console\. 1. Select the execution role that you created\. 1. Choose **Delete role**\. 1. Choose **Yes, delete**\. **To delete the S3 buckets** 1. Open the [Amazon S3 console\.](https://console.aws.amazon.com/s3/home#) 1. Select the source bucket you created\. 1. Choose **Delete**\. 1. Enter the name of the source bucket in the text box\. 1. Choose **Confirm**\.
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/with-s3-example.md
e3dba90f2d86-0
Sample code is available for the following languages\. **Topics** + [Node\.js 8](#with-sns-example-deployment-pkg-nodejs) + [Java 11](#with-sns-example-deployment-pkg-java) + [Go](#with-sns-example-deployment-pkg-go) + [Python 3](#with-sns-example-deployment-pkg-python)
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/with-sns-create-package.md
4696c73d44f8-0
The following example processes messages from Amazon SNS, and logs their contents\. **Example index\.js** ``` console.log('Loading function'); exports.handler = function(event, context, callback) { // console.log('Received event:', JSON.stringify(event, null, 4)); var message = event.Records[0].Sns.Message; console.log('Message received from SNS:', message); callback(null, "Success"); }; ``` Zip up the sample code to create a deployment package\. For instructions, see [AWS Lambda deployment package in Node\.js](nodejs-package.md)\.
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/with-sns-create-package.md
7cf7a8fc618f-0
The following example processes messages from Amazon SNS, and logs their contents\. **Example LambdaWithSNS\.java** ``` package example; import java.text.SimpleDateFormat; import java.util.Calendar; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.events.SNSEvent; public class LogEvent implements RequestHandler<SNSEvent, Object> { public Object handleRequest(SNSEvent request, Context context){ String timeStamp = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss").format(Calendar.getInstance().getTime()); context.getLogger().log("Invocation started: " + timeStamp); context.getLogger().log(request.getRecords().get(0).getSNS().getMessage()); timeStamp = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss").format(Calendar.getInstance().getTime()); context.getLogger().log("Invocation completed: " + timeStamp); return null; } } ```
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/with-sns-create-package.md
7cf7a8fc618f-1
return null; } } ``` **Dependencies** + `aws-lambda-java-core` + `aws-lambda-java-events` Build the code with the Lambda library dependencies to create a deployment package\. For instructions, see [AWS Lambda deployment package in Java](java-package.md)\.
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/with-sns-create-package.md
aea241af79d5-0
The following example processes messages from Amazon SNS, and logs their contents\. **Example lambda\_handler\.go** ``` package main import ( "context" "fmt" "github.com/aws/aws-lambda-go/lambda" "github.com/aws/aws-lambda-go/events" ) func handler(ctx context.Context, snsEvent events.SNSEvent) { for _, record := range snsEvent.Records { snsRecord := record.SNS fmt.Printf("[%s %s] Message = %s \n", record.EventSource, snsRecord.Timestamp, snsRecord.Message) } } func main() { lambda.Start(handler) } ``` Build the executable with `go build` and create a deployment package\. For instructions, see [AWS Lambda deployment package in Go](golang-package.md)\.
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/with-sns-create-package.md
0cd781fa1de7-0
The following example processes messages from Amazon SNS, and logs their contents\. **Example lambda\_handler\.py** ``` from __future__ import print_function import json print('Loading function') def lambda_handler(event, context): #print("Received event: " + json.dumps(event, indent=2)) message = event['Records'][0]['Sns']['Message'] print("From SNS: " + message) return message ``` Zip up the sample code to create a deployment package\. For instructions, see [AWS Lambda deployment package in Python](python-package.md)\.
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/with-sns-create-package.md
2256839c147b-0
AWS Lambda supports standard rate and cron expressions for frequencies of up to once per minute\. CloudWatch Events rate expressions have the following format\. ``` rate(Value Unit) ``` Where *Value* is a positive integer and *Unit* can be minute\(s\), hour\(s\), or day\(s\)\. For a singular value the unit must be singular \(for example, `rate(1 day)`\), otherwise plural \(for example, `rate(5 days)`\)\. **Rate expression examples** | Frequency | Expression | | --- | --- | | Every 5 minutes | `rate(5 minutes)` | | Every hour | `rate(1 hour)` | | Every seven days | `rate(7 days)` | Cron expressions have the following format\. ``` cron(Minutes Hours Day-of-month Month Day-of-week Year) ``` **Cron expression examples** | Frequency | Expression | | --- | --- | | 10:15 AM \(UTC\) every day | `cron(15 10 * * ? *)` | | 6:00 PM Monday through Friday | `cron(0 18 ? * MON-FRI *)` | | 8:00 AM on the first day of the month | `cron(0 8 1 * ? *)` |
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/services-cloudwatchevents-expressions.md
2256839c147b-1
| 8:00 AM on the first day of the month | `cron(0 8 1 * ? *)` | | Every 10 min on weekdays | `cron(0/10 * ? * MON-FRI *)` | | Every 5 minutes between 8:00 AM and 5:55 PM weekdays | `cron(0/5 8-17 ? * MON-FRI *)` | | 9:00 AM on the first Monday of each month | `cron(0 9 ? * 2#1 *)` | Note the following: + If you are using the Lambda console, do not include the `cron` prefix to your expression\. + One of the day\-of\-month or day\-of\-week values must be a question mark \(`?`\)\. For more information, see [Schedule expressions for rules](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html) in the *CloudWatch Events User Guide*\.
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/services-cloudwatchevents-expressions.md
0d9dacec22bf-0
You can use the AWS Command Line Interface to manage functions and other AWS Lambda resources\. The AWS CLI uses the AWS SDK for Python \(Boto\) to interact with the Lambda API\. You can use it to learn about the API, and apply that knowledge in building applications that use Lambda with the AWS SDK\. In this tutorial, you manage and invoke Lambda functions with the AWS CLI\.
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/gettingstarted-awscli.md
a1fce76a9fe8-0
This tutorial assumes that you have some knowledge of basic Lambda operations and the Lambda console\. If you haven't already, follow the instructions in [Getting started with AWS Lambda](getting-started.md) to create your first Lambda function\. To follow the procedures in this guide, you will need a command line terminal or shell to run commands\. Commands are shown in listings preceded by a prompt symbol \($\) and the name of the current directory, when appropriate: ``` ~/lambda-project$ this is a command this is output ``` For long commands, an escape character \(`\`\) is used to split a command over multiple lines\. On Linux and macOS, use your preferred shell and package manager\. On Windows 10, you can [install the Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to get a Windows\-integrated version of Ubuntu and Bash\. This tutorial uses the AWS Command Line Interface \(AWS CLI\) to call service API operations\. To install the AWS CLI, see [Installing the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html) in the AWS Command Line Interface User Guide\.
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/gettingstarted-awscli.md
1323408bf32c-0
Create the [execution role](lambda-intro-execution-role.md) that gives your function permission to access AWS resources\. To create an execution role with the AWS CLI, use the `create-role` command\. ``` $ aws iam create-role --role-name lambda-ex --assume-role-policy-document file://trust-policy.json { "Role": { "Path": "/", "RoleName": "lambda-ex", "RoleId": "AROAQFOXMPL6TZ6ITKWND", "Arn": "arn:aws:iam::123456789012:role/lambda-ex", "CreateDate": "2020-01-17T23:19:12Z", "AssumeRolePolicyDocument": { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "lambda.amazonaws.com" }, "Action": "sts:AssumeRole" } ] } } } ```
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/gettingstarted-awscli.md
1323408bf32c-1
} ] } } } ``` The `trust-policy.json` file is a JSON file in the current directory that defines the [trust policy](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_terms-and-concepts.html) for the role\. This trust policy allows Lambda to use the role's permissions by giving the service principal `lambda.amazonaws.com` permission to call the AWS Security Token Service `AssumeRole` action\. **Example trust\-policy\.json** ``` { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "lambda.amazonaws.com" }, "Action": "sts:AssumeRole" } ] } ``` You can also specify the trust policy inline\. Requirements for escaping quotes in the JSON string vary depending on your shell\. ```
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/gettingstarted-awscli.md
1323408bf32c-2
You can also specify the trust policy inline\. Requirements for escaping quotes in the JSON string vary depending on your shell\. ``` $ aws iam create-role --role-name lambda-ex --assume-role-policy-document '{"Version": "2012-10-17","Statement": [{ "Effect": "Allow", "Principal": {"Service": "lambda.amazonaws.com"}, "Action": "sts:AssumeRole"}]}' ``` To add permissions to the role, use the `attach-policy-to-role` command\. Start by adding the `AWSLambdaBasicExecutionRole` managed policy\. ``` $ aws iam attach-role-policy --role-name lambda-ex --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole ``` The **AWSLambdaBasicExecutionRole** policy has the permissions that the function needs to write logs to CloudWatch Logs\.
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/gettingstarted-awscli.md
7a546af0d2d6-0
The following example logs the values of environment variables and the event object\. **Example index\.js** ``` exports.handler = async function(event, context) { console.log("ENVIRONMENT VARIABLES\n" + JSON.stringify(process.env, null, 2)) console.log("EVENT\n" + JSON.stringify(event, null, 2)) return context.logStreamName } ``` **To create the function** 1. Copy the sample code into a file named `index.js`\. 1. Create a deployment package\. ``` $ zip function.zip index.js ``` 1. Create a Lambda function with the `create-function` command\. Replace the highlighted text in the role ARN with your account ID\. ``` $ aws lambda create-function --function-name my-function \ --zip-file fileb://function.zip --handler index.handler --runtime nodejs12.x \ --role arn:aws:iam::123456789012:role/lambda-ex { "FunctionName": "my-function", "FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function",
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/gettingstarted-awscli.md
7a546af0d2d6-1
"FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function", "Runtime": "nodejs12.x", "Role": "arn:aws:iam::123456789012:role/lambda-ex", "Handler": "index.handler", "CodeSha256": "FpFMvUhayLkOoVBpNuNiIVML/tuGv2iJQ7t0yWVTU8c=", "Version": "$LATEST", "TracingConfig": { "Mode": "PassThrough" }, "RevisionId": "88ebe1e1-bfdf-4dc3-84de-3017268fa1ff", ... } ``` To get logs for an invocation from the command line, use the `--log-type` option\. The response includes a `LogResult` field that contains up to 4 KB of base64\-encoded logs from the invocation\. ``` $ aws lambda invoke --function-name my-function out --log-type Tail { "StatusCode": 200,
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/gettingstarted-awscli.md
7a546af0d2d6-2
$ aws lambda invoke --function-name my-function out --log-type Tail { "StatusCode": 200, "LogResult": "U1RBUlQgUmVxdWVzdElkOiA4N2QwNDRiOC1mMTU0LTExZTgtOGNkYS0yOTc0YzVlNGZiMjEgVmVyc2lvb...", "ExecutedVersion": "$LATEST" } ``` You can use the `base64` utility to decode the logs\. ``` $ aws lambda invoke --function-name my-function out --log-type Tail \ --query 'LogResult' --output text | base64 -d START RequestId: 57f231fb-1730-4395-85cb-4f71bd2b87b8 Version: $LATEST "AWS_SESSION_TOKEN": "AgoJb3JpZ2luX2VjELj...", "_X_AMZN_TRACE_ID": "Root=1-5d02e5ca-f5792818b6fe8368e5b51d50;Parent=191db58857df8395;Sampled=0"",ask/lib:/opt/lib", END RequestId: 57f231fb-1730-4395-85cb-4f71bd2b87b8
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/gettingstarted-awscli.md
7a546af0d2d6-3
END RequestId: 57f231fb-1730-4395-85cb-4f71bd2b87b8 REPORT RequestId: 57f231fb-1730-4395-85cb-4f71bd2b87b8 Duration: 79.67 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 73 MB ``` The `base64` utility is available on Linux, macOS, and [Ubuntu on Windows](https://docs.microsoft.com/en-us/windows/wsl/install-win10)\. For macOS, the command is `base64 -D`\. To get full log events from the command line, you can include the log stream name in the output of your function, as shown in the preceding example\. The following example script invokes a function named `my-function` and downloads the last five log events\. **Example get\-logs\.sh Script** This example requires that `my-function` returns a log stream ID\. ``` #!/bin/bash aws lambda invoke --function-name my-function --payload '{"key": "value"}' out sed -i'' -e 's/"//g' out sleep 15 aws logs get-log-events --log-group-name /aws/lambda/my-function --log-stream-name $(cat out) --limit 5 ```
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/gettingstarted-awscli.md
7a546af0d2d6-4
``` The script uses `sed` to remove quotes from the output file, and sleeps for 15 seconds to allow time for the logs to be available\. The output includes the response from Lambda and the output from the `get-log-events` command\. ``` $ ./get-logs.sh { "StatusCode": 200, "ExecutedVersion": "$LATEST" } { "events": [ { "timestamp": 1559763003171, "message": "START RequestId: 4ce9340a-b765-490f-ad8a-02ab3415e2bf Version: $LATEST\n", "ingestionTime": 1559763003309 }, { "timestamp": 1559763003173, "message": "2019-06-05T19:30:03.173Z\t4ce9340a-b765-490f-ad8a-02ab3415e2bf\tINFO\tENVIRONMENT VARIABLES\r{\r \"AWS_LAMBDA_FUNCTION_VERSION\": \"$LATEST\",\r ...", "ingestionTime": 1559763018353 }, { "timestamp": 1559763003173,
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/gettingstarted-awscli.md
7a546af0d2d6-5
}, { "timestamp": 1559763003173, "message": "2019-06-05T19:30:03.173Z\t4ce9340a-b765-490f-ad8a-02ab3415e2bf\tINFO\tEVENT\r{\r \"key\": \"value\"\r}\n", "ingestionTime": 1559763018353 }, { "timestamp": 1559763003218, "message": "END RequestId: 4ce9340a-b765-490f-ad8a-02ab3415e2bf\n", "ingestionTime": 1559763018353 }, { "timestamp": 1559763003218, "message": "REPORT RequestId: 4ce9340a-b765-490f-ad8a-02ab3415e2bf\tDuration: 26.73 ms\tBilled Duration: 100 ms \tMemory Size: 128 MB\tMax Memory Used: 75 MB\t\n", "ingestionTime": 1559763018353 } ],
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/gettingstarted-awscli.md
7a546af0d2d6-6
"ingestionTime": 1559763018353 } ], "nextForwardToken": "f/34783877304859518393868359594929986069206639495374241795", "nextBackwardToken": "b/34783877303811383369537420289090800615709599058929582080" } ```
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/gettingstarted-awscli.md
6f39dec1b4da-0
Execute the following AWS CLI `list-functions` command to retrieve a list of functions that you have created\. ``` $ aws lambda list-functions --max-items 10 { "Functions": [ { "FunctionName": "cli", "FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function", "Runtime": "nodejs12.x", "Role": "arn:aws:iam::123456789012:role/lambda-ex", "Handler": "index.handler", ... }, { "FunctionName": "random-error", "FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:random-error", "Runtime": "nodejs12.x", "Role": "arn:aws:iam::123456789012:role/lambda-role", "Handler": "index.handler", ... }, ... ],
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/gettingstarted-awscli.md
6f39dec1b4da-1
"Handler": "index.handler", ... }, ... ], "NextToken": "eyJNYXJrZXIiOiBudWxsLCAiYm90b190cnVuY2F0ZV9hbW91bnQiOiAxMH0=" } ``` In response, Lambda returns a list of up to 10 functions\. If there are more functions you can retrieve, `NextToken` provides a marker you can use in the next `list-functions` request\. The following `list-functions` AWS CLI command is an example that shows the `--starting-token` parameter\. ``` $ aws lambda list-functions --max-items 10 --starting-token eyJNYXJrZXIiOiBudWxsLCAiYm90b190cnVuY2F0ZV9hbW91bnQiOiAxMH0= ```
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/gettingstarted-awscli.md
b19127564b5c-0
The Lambda CLI `get-function` command returns Lambda function metadata and a presigned URL that you can use to download the function's deployment package\. ``` $ aws lambda get-function --function-name my-function { "Configuration": { "FunctionName": "my-function", "FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function", "Runtime": "nodejs12.x", "Role": "arn:aws:iam::123456789012:role/lambda-ex", "CodeSha256": "FpFMvUhayLkOoVBpNuNiIVML/tuGv2iJQ7t0yWVTU8c=", "Version": "$LATEST", "TracingConfig": { "Mode": "PassThrough" }, "RevisionId": "88ebe1e1-bfdf-4dc3-84de-3017268fa1ff", ... }, "Code": { "RepositoryType": "S3",
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/gettingstarted-awscli.md
b19127564b5c-1
... }, "Code": { "RepositoryType": "S3", "Location": "https://awslambda-us-east-2-tasks.s3.us-east-2.amazonaws.com/snapshots/123456789012/my-function-4203078a-b7c9-4f35-..." } } ``` For more information, see [GetFunction](API_GetFunction.md)\.
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/gettingstarted-awscli.md
b76ad6036374-0
Execute the following `delete-function` command to delete the `my-function` function\. ``` $ aws lambda delete-function --function-name my-function ``` Delete the IAM role you created in the IAM console\. For information about deleting a role, see [Deleting roles or instance profiles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_manage_delete.html) in the *IAM User Guide*\.
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/gettingstarted-awscli.md
8cbc3d9d0745-0
Use rolling deployments to control the risks associated with introducing new versions of your Lambda function\. In a rolling deployment, the system automatically deploys the new version of the function and gradually sends an increasing amount of traffic to the new version\. The amount of traffic and rate of increase are parameters that you can configure\. You configure a rolling deployment by using AWS CodeDeploy and AWS SAM\. CodeDeploy is a service that automates application deployments to Amazon computing platforms such as Amazon EC2 and AWS Lambda\. For more information, see [What is CodeDeploy?](https://docs.aws.amazon.com/codedeploy/latest/userguide/welcome.html)\. By using CodeDeploy to deploy your Lambda function, you can easily monitor the status of the deployment and initiate a rollback if you detect any issues\. AWS SAM is an open\-source framework for building serverless applications\. You create an AWS SAM template \(in YAML format\) to specify the configuration of the components required for the rolling deployment\. AWS SAM uses the template to create and configure the components\. For more information, see [What is the AWS Serverless Application Model?](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/what-is-sam.html)\. In a rolling deployment, AWS SAM performs these tasks: + It configures your Lambda function and creates an alias\. The alias routing configuration is the underlying capability that implements the rolling deployment\. + It creates a CodeDeploy application and deployment group\.
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/lambda-rolling-deployments.md
8cbc3d9d0745-1
The alias routing configuration is the underlying capability that implements the rolling deployment\. + It creates a CodeDeploy application and deployment group\. The deployment group manages the rolling deployment and the rollback \(if needed\)\. + It detects when you create a new version of your Lambda function\. + It triggers CodeDeploy to start the deployment of the new version\.
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/lambda-rolling-deployments.md
0f6d04c730c4-0
The following example shows an [AWS SAM template](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-template-basics.html) for a simple rolling deployment\. ``` AWSTemplateFormatVersion : '2010-09-09' Transform: AWS::Serverless-2016-10-31 Description: A sample SAM template for deploying Lambda functions. Resources:
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/lambda-rolling-deployments.md
d0af78074e99-0
myDateTimeFunction: Type: [AWS::Serverless::Function](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-resource-function.html) Properties: Handler: myDateTimeFunction.handler Runtime: nodejs12.x
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/lambda-rolling-deployments.md
c9f3ecd69624-0
AutoPublishAlias: live DeploymentPreference:
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/lambda-rolling-deployments.md
4351eae6e2c8-0
Type: Linear10PercentEvery2Minutes ``` This template defines a Lambda function named `myDateTimeFunction` with the following properties\. **AutoPublishAlias ** The `AutoPublishAlias` property creates an alias named `live`\. In addition, the AWS SAM framework automatically detects when you save new code for the function\. The framework then publishes a new function version and updates the `live` alias to point to the new version\. **DeploymentPreference** The `DeploymentPreference` property determines the rate at which the CodeDeploy application shifts traffic from the original version of the Lambda function to the new version\. The value `Linear10PercentEvery2Minutes` shifts an additional ten percent of the traffic to the new version every two minutes\. For a list of the predefined deployment configurations, see [Deployment configurations](https://docs.aws.amazon.com/codedeploy/latest/userguide/deployment-configurations.html)\. For a detailed tutorial on how to use CodeDeploy with Lambda functions, see [Deploy an updated Lambda function with CodeDeploy](https://docs.aws.amazon.com/codedeploy/latest/userguide/tutorial-lambda-sam.html)\.
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/lambda-rolling-deployments.md
266b443e28fb-0
You can use an AWS Lambda function to process messages in an Amazon Simple Queue Service \(Amazon SQS\) queue\. Lambda [event source mappings](invocation-eventsourcemapping.md) support [standard queues](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/standard-queues.html) and [first\-in, first\-out \(FIFO\) queues](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/fifo-queues.html)\. With Amazon SQS, you can offload tasks from one component of your application by sending them to a queue and processing them asynchronously\. Lambda polls the queue and invokes your function [synchronously](invocation-sync.md) with an event that contains queue messages\. Lambda reads messages in batches and invokes your function once for each batch\. When your function successfully processes a batch, Lambda deletes its messages from the queue\. The following example shows an event for a batch of two messages\. **Example Amazon SQS message event \(standard queue\)** ``` { "Records": [ { "messageId": "059f36b4-87a3-44ab-83d2-661975830a7d", "receiptHandle": "AQEBwJnKyrHigUMZj6rYigCgxlaS3SLy0a...",
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/with-sqs.md
266b443e28fb-1
"receiptHandle": "AQEBwJnKyrHigUMZj6rYigCgxlaS3SLy0a...", "body": "Test message.", "attributes": { "ApproximateReceiveCount": "1", "SentTimestamp": "1545082649183", "SenderId": "AIDAIENQZJOLO23YVJ4VO", "ApproximateFirstReceiveTimestamp": "1545082649185" }, "messageAttributes": {}, "md5OfBody": "e4e68fb7bd0e697a0ae8f1bb342846b3", "eventSource": "aws:sqs", "eventSourceARN": "arn:aws:sqs:us-east-2:123456789012:my-queue", "awsRegion": "us-east-2" }, { "messageId": "2e1424d4-f796-459a-8184-9c92662be6da", "receiptHandle": "AQEBzWwaftRI0KuVm4tP+/7q1rGgNqicHq...", "body": "Test message.",
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/with-sqs.md
266b443e28fb-2
"body": "Test message.", "attributes": { "ApproximateReceiveCount": "1", "SentTimestamp": "1545082650636", "SenderId": "AIDAIENQZJOLO23YVJ4VO", "ApproximateFirstReceiveTimestamp": "1545082650649" }, "messageAttributes": {}, "md5OfBody": "e4e68fb7bd0e697a0ae8f1bb342846b3", "eventSource": "aws:sqs", "eventSourceARN": "arn:aws:sqs:us-east-2:123456789012:my-queue", "awsRegion": "us-east-2" } ] } ``` For FIFO queues, records contain additional attributes that are related to deduplication and sequencing\. **Example Amazon SQS message event \(FIFO queue\)** ``` { "Records": [ { "messageId": "11d6ee51-4cc7-4302-9e22-7cd8afdaadf5",
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/with-sqs.md
266b443e28fb-3
{ "messageId": "11d6ee51-4cc7-4302-9e22-7cd8afdaadf5", "receiptHandle": "AQEBBX8nesZEXmkhsmZeyIE8iQAMig7qw...", "body": "Test message.", "attributes": { "ApproximateReceiveCount": "1", "SentTimestamp": "1573251510774", "SequenceNumber": "18849496460467696128", "MessageGroupId": "1", "SenderId": "AIDAIO23YVJENQZJOL4VO", "MessageDeduplicationId": "1", "ApproximateFirstReceiveTimestamp": "1573251510774" }, "messageAttributes": {}, "md5OfBody": "e4e68fb7bd0e697a0ae8f1bb342846b3", "eventSource": "aws:sqs", "eventSourceARN": "arn:aws:sqs:us-east-2:123456789012:fifo.fifo", "awsRegion": "us-east-2" } ]
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/with-sqs.md
266b443e28fb-4
"awsRegion": "us-east-2" } ] } ``` When Lambda reads a batch, the messages stay in the queue but become hidden for the length of the queue's [visibility timeout](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html)\. If your function successfully processes the batch, Lambda deletes the messages from the queue\. If your function is [throttled](invocation-scaling.md), returns an error, or doesn't respond, the message becomes visible again\. All messages in a failed batch return to the queue, so your function code must be able to process the same message multiple times without side effects\.
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/with-sqs.md
baa1ea993ecb-0
For standard queues, Lambda uses [long polling](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-long-polling.html) to poll a queue until it becomes active\. When messages are available, Lambda reads up to 5 batches and sends them to your function\. If messages are still available, Lambda increases the number of processes that are reading batches by up to 60 more instances per minute\. The maximum number of batches that can be processed simultaneously by an event source mapping is 1000\. For FIFO queues, Lambda sends messages to your function in the order that it receives them\. When you send a message to a FIFO queue, you specify a [message group ID](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/using-messagegroupid-property.html)\. Amazon SQS ensures that messages in the same group are delivered to Lambda in order\. Lambda sorts the messages into groups and sends only one batch at a time for a group\. If the function returns an error, all retries are attempted on the affected messages before Lambda receives additional messages from the same group\. Your function can scale in concurrency to the number of active message groups\. For more information, see [SQS FIFO as an event source](https://aws.amazon.com/blogs/compute/new-for-aws-lambda-sqs-fifo-as-an-event-source/) on the AWS Compute Blog\.
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/with-sqs.md
15618243f4e1-0
[Create an SQS queue](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/) to serve as an event source for your Lambda function\. Then configure the queue to allow time for your Lambda function to process each batch of events—and for Lambda to retry in response to throttling errors as it scales up\. To allow your function time to process each batch of records, set the source queue's visibility timeout to at least 6 times the [timeout](configuration-console.md) that you configure on your function\. The extra time allows for Lambda to retry if your function execution is throttled while your function is processing a previous batch\. If a message fails to be processed multiple times, Amazon SQS can send it to a [dead\-letter queue](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html)\. When your function returns an error, Lambda leaves it in the queue\. After the visibility timeout occurs, Lambda receives the message again\. To send messages to a second queue after a number of receives, configure a dead\-letter queue on your source queue\. **Note** Make sure that you configure the dead\-letter queue on the source queue, not on the Lambda function\. The dead\-letter queue that you configure on a function is used for the function's [asynchronous invocation queue](invocation-async.md), not for event source queues\.
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/with-sqs.md
15618243f4e1-1
If your function returns an error, or can't be invoked because it's at maximum concurrency, processing might succeed with additional attempts\. To give messages a better chance to be processed before sending them to the dead\-letter queue, set the `maxReceiveCount` on the source queue's redrive policy to at least **5**\.
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/with-sqs.md
3bbd227571a4-0
Lambda needs the following permissions to manage messages in your Amazon SQS queue\. Add them to your function's execution role\. + [sqs:ReceiveMessage](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_ReceiveMessage.html) + [sqs:DeleteMessage](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_DeleteMessage.html) + [sqs:GetQueueAttributes](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_GetQueueAttributes.html) For more information, see [AWS Lambda execution role](lambda-intro-execution-role.md)\.
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/with-sqs.md
1db18a381c17-0
Create an event source mapping to tell Lambda to send items from your queue to a Lambda function\. You can create multiple event source mappings to process items from multiple queues with a single function\. When Lambda invokes the target function, the event can contain multiple items, up to a configurable maximum *batch size*\. To configure your function to read from Amazon SQS in the Lambda console, create an **SQS** trigger\. **To create a trigger** 1. Open the Lambda console [Functions page](https://console.aws.amazon.com/lambda/home#/functions)\. 1. Choose a function\. 1. Under **Designer**, choose **Add trigger**\. 1. Choose a trigger type\. 1. Configure the required options and then choose **Add**\. Lambda supports the following options for Amazon SQS event sources\. **Event source options** + **SQS queue** – The Amazon SQS queue to read records from\. + **Batch size** – The number of items to read from the queue in each batch, up to 10\. The event might contain fewer items if the batch that Lambda read from the queue had fewer items\. + **Enabled** – Set to true to enable the event source mapping\. Set to false to stop processing records\. **Note**
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/with-sqs.md
1db18a381c17-1
+ **Enabled** – Set to true to enable the event source mapping\. Set to false to stop processing records\. **Note** Amazon SQS has a perpetual free tier for requests\. Beyond the free tier, Amazon SQS charges per million requests\. While your event source mapping is active, Lambda makes requests to the queue to get items\. For pricing details, see [Amazon Simple Queue Service pricing](https://aws.amazon.com/sqs/pricing)\. To manage the event source configuration later, choose the trigger in the designer\. Configure your function timeout to allow enough time to process an entire batch of items\. If items take a long time to process, choose a smaller batch size\. A large batch size can improve efficiency for workloads that are very fast or have a lot of overhead\. However, if your function returns an error, all items in the batch return to the queue\. If you configure [reserved concurrency](configuration-concurrency.md) on your function, set a minimum of 5 concurrent executions to reduce the chance of throttling errors when Lambda invokes your function\.
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/with-sqs.md
cba2dbe94525-0
To manage event source mappings with the AWS CLI or AWS SDK, use the following API actions: + [CreateEventSourceMapping](API_CreateEventSourceMapping.md) + [ListEventSourceMappings](API_ListEventSourceMappings.md) + [GetEventSourceMapping](API_GetEventSourceMapping.md) + [UpdateEventSourceMapping](API_UpdateEventSourceMapping.md) + [DeleteEventSourceMapping](API_DeleteEventSourceMapping.md) The following example uses the AWS CLI to map a function named `my-function` to an Amazon SQS queue that is specified by its Amazon Resource Name \(ARN\), with a batch size of 5\. ``` $ aws lambda create-event-source-mapping --function-name my-function --batch-size 5 \ --event-source-arn arn:aws:sqs:us-east-2:123456789012:my-queue { "UUID": "2b733gdc-8ac3-cdf5-af3a-1827b3b11284", "BatchSize": 5, "EventSourceArn": "arn:aws:sqs:us-east-2:123456789012:my-queue",
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/with-sqs.md
cba2dbe94525-1
"EventSourceArn": "arn:aws:sqs:us-east-2:123456789012:my-queue", "FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function", "LastModified": 1541139209.351, "State": "Creating", "StateTransitionReason": "USER_INITIATED" } ```
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/with-sqs.md
20105ee3b1cd-0
The handler is the method in your Lambda function that processes events\. When you invoke a function, the [runtime](lambda-runtimes.md) runs the handler method\. When the handler exits or returns a response, it becomes available to handle another event\. The following example function logs the contents of the event object and returns the location of the logs\. **Example index\.js** ``` exports.handler = async function(event, context) { console.log("EVENT: \n" + JSON.stringify(event, null, 2)) return context.logStreamName } ``` When you [configure a function](configuration-console.md), the value of the handler setting is the file name and the name of the exported handler module, separated by a dot\. The default in the console and for examples in this guide is `index.handler`\. This indicates the `handler` module that's exported by `index.js`\. The runtime passes three arguments to the handler method\. The first argument is the `event` object, which contains information from the invoker\. The invoker passes this information as a JSON\-formatted string when it calls [Invoke](API_Invoke.md), and the runtime converts it to an object\. When an AWS service invokes your function, the event structure [varies by service](lambda-services.md)\.
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/nodejs-handler.md
20105ee3b1cd-1
The second argument is the [context object](nodejs-context.md), which contains information about the invocation, function, and execution environment\. In the preceding example, the function gets the name of the [log stream](nodejs-logging.md) from the context object and returns it to the invoker\. The third argument, `callback`, is a function that you can call in [non\-async handlers](#nodejs-handler-sync) to send a response\. The callback function takes two arguments: an `Error` and a response\. When you call it, Lambda waits for the event loop to be empty and then returns the response or error to the invoker\. The response object must be compatible with `JSON.stringify`\. For async handlers, you return a response, error, or promise to the runtime instead of using `callback`\.
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/nodejs-handler.md
fa3f588e394c-0
For async handlers, you can use `return` and `throw` to send a response or error, respectively\. Functions must use the `async` keyword to use these methods to return a response or error\. If your code performs an asynchronous task, return a promise to make sure that it finishes running\. When you resolve or reject the promise, Lambda sends the response or error to the invoker\. **Example index\.js file – HTTP request with async handler and promises** ``` const https = require('https') let url = "https://docs.aws.amazon.com/lambda/latest/dg/welcome.html" exports.handler = async function(event) { const promise = new Promise(function(resolve, reject) { https.get(url, (res) => { resolve(res.statusCode) }).on('error', (e) => { reject(Error(e)) }) }) return promise } ``` For libraries that return a promise, you can return that promise directly to the runtime\. **Example index\.js file – AWS SDK with async handler and promises** ``` const AWS = require('aws-sdk') const s3 = new AWS.S3()
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/nodejs-handler.md
fa3f588e394c-1
const AWS = require('aws-sdk') const s3 = new AWS.S3() exports.handler = async function(event) { return s3.listBuckets().promise() } ```
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/nodejs-handler.md
6f231bfffb77-0
The following example function checks a URL and returns the status code to the invoker\. **Example index\.js file – HTTP request with callback** ``` const https = require('https') let url = "https://docs.aws.amazon.com/lambda/latest/dg/welcome.html" exports.handler = function(event, context, callback) { https.get(url, (res) => { callback(null, res.statusCode) }).on('error', (e) => { callback(Error(e)) }) } ``` For non\-async handlers, function execution continues until the [event loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/) is empty or the function times out\. The response isn't sent to the invoker until all event loop tasks are finished\. If the function times out, an error is returned instead\. You can configure the runtime to send the response immediately by setting [context\.callbackWaitsForEmptyEventLoop](nodejs-context.md) to false\. In the following example, the response from Amazon S3 is returned to the invoker as soon as it's available\. The timeout running on the event loop is frozen, and it continues running the next time the function is invoked\.
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/nodejs-handler.md
6f231bfffb77-1
**Example index\.js file – callbackWaitsForEmptyEventLoop** ``` const AWS = require('aws-sdk') const s3 = new AWS.S3() exports.handler = function(event, context, callback) { context.callbackWaitsForEmptyEventLoop = false s3.listBuckets(null, callback) setTimeout(function () { console.log('Timeout complete.') }, 5000) } ```
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/nodejs-handler.md
3ce3af7f6214-0
The [dead\-letter queue](https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html#dlq) for failed asynchronous invocations\.
https://github.com/siagholami/aws-documentation/tree/main/documents/aws-lambda-developer-guide/doc_source/API_DeadLetterConfig.md