Lambda DG
Lambda DG
Developer Guide
Table of Contents
What Is AWS Lambda? .................................................................................................................. 1
When should I Use Lambda? ................................................................................................... 1
Are You a First-time User of AWS Lambda? ............................................................................... 2
How It Works ................................................................................................................................ 3
Example 1 ............................................................................................................................ 4
Example 2 ............................................................................................................................ 5
Example 3: Custom Application Publishes Events and Invokes a Lambda Function ........................... 6
Lambda Function .................................................................................................................. 8
Compute Requirements Lambda Function Configuration .................................................... 8
Invocation Types ............................................................................................................ 9
How Does AWS Lambda Run My Code? The Container Model .............................................. 9
Event Source Mapping ......................................................................................................... 10
Event Source Mapping for AWS Services ........................................................................ 11
Event Source Mapping for AWS Stream-based Services ..................................................... 12
Event Source Mapping for Custom Applications ................................................................ 13
Supported Event Sources ..................................................................................................... 15
Amazon S3 ................................................................................................................. 15
Amazon DynamoDB ..................................................................................................... 16
Amazon Kinesis Streams .............................................................................................. 16
Amazon Simple Notification Service ................................................................................ 16
Amazon Simple Email Service ....................................................................................... 17
Amazon Cognito .......................................................................................................... 17
AWS CloudFormation ................................................................................................... 17
Amazon CloudWatch Logs ............................................................................................ 18
Amazon CloudWatch Events .......................................................................................... 18
Scheduled Events (powered by Amazon CloudWatch Events) ............................................. 18
AWS Config ................................................................................................................ 18
Amazon Echo ............................................................................................................. 19
Amazon API Gateway ................................................................................................... 19
Other Event Sources: Invoking a Lambda Function On Demand ........................................... 19
Sample Event Data ...................................................................................................... 20
Concurrent Executions ......................................................................................................... 28
Concurrent Execution Request Rate ............................................................................... 28
Concurrent Executions Safety Limit ................................................................................. 28
Retries on Errors ................................................................................................................. 30
Permissions Model ............................................................................................................... 31
Manage Permissions: Using an IAM Role (Execution Role) ................................................. 31
Manage Permissions: Using a Lambda Function Policy ...................................................... 32
Execution Environment ......................................................................................................... 33
Getting Started ............................................................................................................................ 35
Step 1: Set Up an AWS Account and the AWS CLI .................................................................... 35
Step 1.1: Set Up an Account .......................................................................................... 35
Step 1.2: Set Up the AWS CLI ........................................................................................ 38
Step 2: Create a HelloWorld Lambda Function and Explore the Console ....................................... 39
Preparing for the Getting Started .................................................................................... 39
Step 2.1: Create a Hello World Lambda Function ............................................................... 39
Step 2.2: Invoke the Lambda Function ............................................................................. 42
Step 2.3: (Optional) Try Other Blueprints .......................................................................... 44
Step 2.4: (Optional) Create a Lambda Function Authored in Java ......................................... 45
What's Next? .............................................................................................................. 46
Building AWS Lambda-Based Applications ....................................................................................... 47
Authoring Code for Your Lambda Function ................................................................................ 48
Deploying Code and Creating a Lambda Function ..................................................................... 48
Creating a Deployment Package ..................................................................................... 49
Uploading a Deployment Package .................................................................................. 49
iii
iv
241
242
242
243
243
245
246
246
247
247
248
251
259
260
261
262
262
263
263
263
265
265
265
266
266
267
267
267
268
268
268
268
269
269
270
270
271
271
273
276
279
283
288
289
291
293
295
297
299
302
304
308
310
312
314
316
318
322
UpdateAlias ..............................................................................................................
UpdateEventSourceMapping ........................................................................................
UpdateFunctionCode ..................................................................................................
UpdateFunctionConfiguration .......................................................................................
Data Types ........................................................................................................................
AliasConfiguration ......................................................................................................
EventSourceMappingConfiguration ...............................................................................
FunctionCode ............................................................................................................
FunctionCodeLocation ................................................................................................
FunctionConfiguration .................................................................................................
VpcConfig .................................................................................................................
VpcConfigResponse ...................................................................................................
Document History ......................................................................................................................
AWS Glossary ...........................................................................................................................
vi
324
326
329
333
337
338
339
340
341
342
344
345
346
350
If you need to manage your own compute resources, Amazon Web Services also offers other compute
services to meet your needs.
Amazon Elastic Compute Cloud (Amazon EC2) service offers flexibility and a wide range of EC2
instance types to choose from. It gives you the option to customize operating systems, network and
security settings, and the entire software stack, but you are responsible for provisioning capacity,
monitoring fleet health and performance, and using Availability Zones for fault tolerance.
Elastic Beanstalk offers an easy-to-use service for deploying and scaling applications onto Amazon
EC2 in which you retain ownership and full control over the underlying EC2 instances.
Data and analytics Suppose you are building an analytics application and storing raw data in a
DynamoDB table. When you write, update, or delete items in a table, DynamoDB streams can publish
item update events to a stream associated with the table. In this case, the event data provides the item
key, event name (such as insert, update, and delete), and other relevant details.You can write a Lambda
function to generate custom metrics by aggregating raw data.
Websites Suppose you are creating a website and you want to host the backend logic on Lambda.
You can invoke your Lambda function over HTTP using Amazon API Gateway as the HTTP endpoint.
Now, your web client can invoke the API, and then API Gateway can route the request to Lambda.
Mobile applications Suppose you have a custom mobile application that produces events. You can
create a Lambda function to process events published by your custom application. For example, in this
scenario you can configure a Lambda function to process the clicks within your custom mobile application.
Each of these event sources uses a specific format for the event data. For more information, see Sample
Events Published by Event Sources (p. 20). When a Lambda function is invoked, it receives the event
as a parameter for the Lambda function.
AWS Lambda supports many AWS services as event sources. For more information, see Supported
Event Sources (p. 15). When you configure these event sources to trigger a Lambda function, the Lambda
function is invoked automatically when events occur. You define event source mapping, which is how
you identify what events to track and which Lambda function to invoke.
In addition to the supported AWS services, user applications can also generate eventsyou can build
your own custom event sources. Custom event sources invoke a Lambda function using the AWS Lambda
Invoke (p. 304) operation. User applications, such as client, mobile, or web applications, can publish events
and invoke Lambda functions on demand using the AWS SDKs or AWS Mobile SDKs, such as the AWS
Mobile SDK for Android.
The following are introductory examples of event sources and how the end-to-end experience works.
3. Amazon S3 invokes your Lambda function using the permissions provided by the execution role. For
more information on execution roles, see Authentication and Access Control for AWS Lambda (p. 240).
Amazon S3 knows which Lambda function to invoke based on the event source mapping that is stored
in the bucket notification configuration.
4. AWS Lambda executes the Lambda function, specifying the event as a parameter.
Note the following:
The event source mapping is maintained within the event source service, Amazon S3 in this scenario.
This is true for all supported AWS event sources except the stream-based sources (Amazon Kinesis
and DynamoDB streams). The next example explains stream-based event sources.
The event source (Amazon S3) invokes the Lambda function (referred to as the push model). Again,
this is true for all supported AWS services except the stream-based event sources.
In order for the event source (Amazon S3) to invoke your Lambda function, you must grant permissions
using the permissions policy attached to the Lambda function.
2. AWS Lambda continuously polls the stream, and invokes the Lambda function when the service detects
new records on the stream. AWS Lambda knows which stream to poll and which Lambda function to
invoke based on the event source mapping you create in Lambda.
AWS Lambda invokes the Lambda function (referred to as the pull model).
AWS Lambda does not need permission to invoke your Lambda function, therefore you don't need to
add any permissions to the permissions policy attached to your Lambda function.
1. The mobile application sends a request to Amazon Cognito with an identity pool ID in the request (you
create the identity pool as part of the setup).
3. The mobile application invokes the Lambda function using the temporary credentials (Cognito Identity).
4. AWS Lambda assumes the execution role to execute your Lambda function on your behalf.
6. AWS Lambda returns results to the mobile application, assuming the app invoked the Lambda function
using the RequestResponse invocation type (referred to as synchronous invocation).
In this example, because the custom application is using the same account credentials as the account
that owns the Lambda function, it does not require additional permissions to invoke the function.
Suggested Reading
If you are new to AWS Lambda, at this time you can continue and read all of the topics in this How It
Works chapter for details. You might also consider exploring the Getting Started (p. 35) exercise first to
get hands-on experience creating and testing a Lambda function, and then read the topics in this chapter.
Additionally, the Building AWS Lambda-Based Applications (p. 47) also provides introductory information
that you might find useful, before you dive deep into the technology.
Lambda Function
After you package up your custom code, including any dependencies, and upload it to AWS Lambda,
you have created a Lambda function.
If you are new to AWS Lambda, you might ask: what type of code can I run as a Lambda function? How
does AWS Lambda execute my code? How does AWS Lambda know the amount of memory and CPU
requirements needed to run my Lambda code? The following sections provide an overview of how a
Lambda function works.
Depending on your scenario, you can build applications where you use the AWS Lambda service to run
all or parts of your application code. For more information, see Building AWS Lambda-Based
Applications (p. 47). How It Works (p. 3) provides examples that illustrate how to create a Lambda
function for specific scenarios.
The sections in this topic provide the following introductory information about Lambda functions:
Topics
Compute Requirements Lambda Function Configuration (p. 8)
Invocation Types (p. 9)
How Does AWS Lambda Run My Code? The Container Model (p. 9)
Optionally, you can update the memory size of your functions using the following AWS CLI command
(using valid 64 MB increments):
$ aws lambda update-function-configuration \
--function-name your function name \
--region region where your function resides \
--memorysize memory amount \
--profile adminuser
For information on setting up and using the AWS CLI, see Step 1: Set Up an AWS Account and the
AWS CLI (p. 35).
Maximum execution time (timeout) You pay for the AWS resources that are used to run your
Lambda function. To prevent your Lambda function from running indefinitely, you specify a timeout.
When the specified timeout is reached, AWS Lambda terminates your Lambda function.
IAM role (execution role) This is the role that AWS Lambda assumes when it executes the Lambda
function on your behalf.
Handler name The handler refers to the method in your code where AWS Lambda begins execution.
AWS Lambda passes any event information, which triggered the invocation, as a parameter to the
handler method.
Invocation Types
AWS Lambda supports synchronous and asynchronous invocation of a Lambda function.You can control
the invocation type only when you invoke a Lambda function (referred to as on-demand invocation). The
following examples illustrate on-demand invocations:
Your custom application invokes a Lambda function.
You manually invoke a Lambda function (for example, using the AWS CLI) for testing purposes.
In both cases, you invoke your Lambda function using the Invoke (p. 304) operation, and you can specify
the invocation type as synchronous or asynchronous.
However, when you are using AWS services as event sources, the invocation type is predetermined for
each of these services. You don't have any control over the invocation type that these event sources use
when they invoke your Lambda function. For example, Amazon S3 always invokes a Lambda function
asynchronously and Amazon Cognito always invokes a Lambda function synchronously. For stream-based
AWS services (Amazon Kinesis Streams and Amazon DynamoDB Streams), AWS Lambda polls the
stream and invokes your Lambda function synchronously.
want to allow for your Lambda function. When a Lambda function is invoked, AWS Lambda launches a
container (that is, an execution environment) based on the configuration settings you provided.
Note
The content of this section is for information only. AWS Lambda manages container creations
and deletion, there is no AWS Lambda API for you to manage containers.
It takes time to set up a container and do the necessary bootstrapping, which adds some latency each
time the Lambda function is invoked. You typically see this latency when a Lambda function is invoked
for the first time or after it has been updated because AWS Lambda tries to reuse the container for
subsequent invocations of the Lambda function.
After a Lambda function is executed, AWS Lambda maintains the container for some time in anticipation
of another Lambda function invocation. In effect, the service freezes the container after a Lambda function
completes, and thaws the container for reuse, if AWS Lambda chooses to reuse the container when the
Lambda function is invoked again. This container reuse approach has the following implications:
Any declarations in your Lambda function code (outside the handler code, see Programming
Model (p. 51)) remains initialized, providing additional optimization when the function is invoked again.
For example, if your Lambda function establishes a database connection, instead of reestablishing the
connection, the original connection is used in subsequent invocations. You can add logic in your code
to check if a connection already exists before creating one.
Each container provides some disk space in the /tmp directory. The directory content remains when
the container is frozen, providing transient cache that can be used for multiple invocations. You can
add extra code to check if the cache has the data that you stored. For disk space size, see AWS Lambda
Limits (p. 238).
Background processes or callbacks initiated by your Lambda function that did not complete when the
function ended resume if AWS Lambda chooses to reuse the container. You should make sure any
background processes or callbacks (in case of Node.js) in your code are complete before the code
exits.
Note
When you write your Lambda function code, do not assume that AWS Lambda always reuses
the container because AWS Lambda may choose not to reuse the container. Depending on
various other factors, AWS Lambda may simply create a new container instead of reusing an
existing container.
Suggested Reading
If you are new to AWS Lambda, we suggest you read through all of the topics in the How It Works section
to familiarize yourself with Lambda. The next topic is Event Source Mapping (p. 10).
After you read all of the topics in the How it Works section, we recommend that you review Building AWS
Lambda-Based Applications (p. 47), try the Getting Started (p. 35) exercise, and then explore the Use
Cases (p. 125). Each use case provides step-by-step instructions for you to set up the end-to-end
experience.
10
AWS Lambda. The configuration is referred to as event source mapping, which maps an event source
to a Lambda function. It enables automatic invocation of your Lambda function when events occur.
Each event source mapping identifies the type of events to publish and the Lambda function to invoke
when events occur. The specific Lambda function then receives the event information as a parameter,
your Lambda function code can then process the event.
Note the following about the event sources. These event sources can be any of the following:
AWS services These are the supported AWS services that can be preconfigured to work with AWS
Lambda. You can group these services as regular AWS services or stream-based services. Amazon
Kinesis Streams and Amazon DynamoDB Streams are stream-based event sources, all others AWS
services do not use stream-based event sources. Where you maintain the event source mapping and
how the Lambda function is invoked depends on whether or not you're using a stream-based event
source.
Custom applications You can have your custom applications publish events and invoke a Lambda
function.
You may be wonderingwhere do I keep the event mapping information? Do I keep it within the event
source or within AWS Lambda? The following sections explain event source mapping for each of these
event source categories. These sections also explain how the Lambda function is invoked and how you
manage permissions to allow invocation of your Lambda function.
Topics
Event Source Mapping for AWS Services (p. 11)
Event Source Mapping for AWS Stream-based Services (p. 12)
Event Source Mapping for Custom Applications (p. 13)
Because the event sources invoke your Lambda function, you need to grant the event source the
necessary permissions using a resource-based policy (referred to as the Lambda function policy). For
more information, see AWS Lambda Permissions Model (p. 31).
The following example illustrates how this model works.
11
3. Amazon S3 invokes your Lambda function according to the event source mapping described in the
bucket notification configuration.
4. AWS Lambda verifies the permissions policy attached to the Lambda function to ensure that Amazon
S3 has the necessary permissions. For more information on permissions policies, see Authentication
and Access Control for AWS Lambda (p. 240)
5. Once AWS Lambda verifies the attached permissions policy, it executes the Lambda function.
Remember that your Lambda function receives the event as a parameter.
12
AWS Lambda needs your permission to poll the stream and read records.You grant these permissions
via the execution role, using the permissions policy associated with role that you specify when you
create your Lambda function. AWS Lambda does not need any permissions to invoke your Lambda
function.
The following example illustrates how this model works.
Example AWS Lambda Pulls Events from an Amazon Kinesis Stream and Invokes a
Lambda Function
The following diagram shows a custom application that writes records to an Amazon Kinesis stream and
how AWS Lambda polls the stream. When AWS Lambda detects a new record on the stream, it invokes
your Lambda function.
Suppose you have a custom application that writes records to an Amazon Kinesis stream. You want to
invoke a Lambda function when new records are detected on the stream. You create a Lambda function
and the necessary event source mapping in AWS Lambda.
2. AWS Lambda continuously polls the stream, and invokes the Lambda function when the service detects
new records on the stream. AWS Lambda knows which stream to poll and which Lambda function to
invoke based on the event source mapping you create in AWS Lambda.
3. Assuming the attached permission policy, which allows AWS Lambda to poll the stream, is verified,
AWS Lambda then executes the Lambda function. For more information on permissions policies, see
Authentication and Access Control for AWS Lambda (p. 240)
The example uses an Amazon Kinesis stream but the same applies when working with a DynamoDB
stream.
13
function must allow cross-account permissions in the permissions policy associated with the Lambda
function.
The following example illustrates how this works.
In the following example, the user application and Lambda function are owned by different AWS accounts.
In this case, the AWS account that owns the Lambda function must have cross-account permissions in
the permissions policy associated with the Lambda function. For more information, see AWS Lambda
Permissions Model (p. 31).
Suggested Reading
If you are new to AWS Lambda, we suggest you read through all of the topics in the How It Works section
to familiarize yourself with Lambda. The next topic is Supported Event Sources (p. 15).
After you read all of the topics in the How it Works section, we recommend that you review Building AWS
Lambda-Based Applications (p. 47), try the Getting Started (p. 35) exercise, and then explore the Use
Cases (p. 125). Each use case provides step-by-step instructions for you to set up the end-to-end
experience.
14
The invocation type that these event sources use when invoking a Lambda function is also preconfigured.
For example, Amazon S3 always invokes a Lambda function asynchronously and Amazon Cognito
invokes a Lambda function synchronously. The only time you can control the invocation type is when
you are invoking the Lambda function yourself using the Invoke (p. 304) operation (for example, invoking
a Lambda function on demand from your custom application).
You can also invoke a Lambda function on demand. For details, see Other Event Sources: Invoking a
Lambda Function On Demand (p. 19).
For examples of events that are published by these event sources, see Sample Events Published by
Event Sources (p. 20).
Topics
Amazon S3 (p. 15)
Amazon DynamoDB (p. 16)
Amazon Kinesis Streams (p. 16)
Amazon Simple Notification Service (p. 16)
Amazon Simple Email Service (p. 17)
Amazon Cognito (p. 17)
AWS CloudFormation (p. 17)
Amazon CloudWatch Logs (p. 18)
Amazon CloudWatch Events (p. 18)
Scheduled Events (powered by Amazon CloudWatch Events) (p. 18)
AWS Config (p. 18)
Amazon Echo (p. 19)
Amazon API Gateway (p. 19)
Other Event Sources: Invoking a Lambda Function On Demand (p. 19)
Sample Events Published by Event Sources (p. 20)
Amazon S3
You can write Lambda functions to process S3 bucket events, such as the object-created or object-deleted
events. For example, when a user uploads a photo to a bucket, you might want Amazon S3 to invoke
your Amazon S3 function so that it reads the image and creates a thumbnail for the photo.
15
You can use the bucket notification configuration feature in Amazon S3 to configure the event source
mapping, identifying the bucket events that you want Amazon S3 to publish and which Lambda function
to invoke.
For an example Amazon S3 event, see Event Message Structure, Amazon S3 Put Sample Event (p. 26),
and Amazon S3 Delete Sample Event (p. 27). For an example use case, see Using AWS Lambda with
Amazon S3 (p. 125).
Amazon S3 invokes your Lambda function asynchronously.
Amazon DynamoDB
You can use Lambda functions as triggers for your Amazon DynamoDB table. Triggers are custom actions
you take in response to updates made to the DynamoDB table. To create a trigger, first you enable
Amazon DynamoDB Streams for your table. AWS Lambda polls the stream and your Lambda function
processes any updates published to the stream.
This is a stream-based event source. For stream-based service, you create event source mapping in
AWS Lambda, identifying the stream to poll and which Lambda function to invoke.
For an example DynamoDB event, see Step 2.3.2: Test the Lambda Function (Invoke Manually) (p. 157)
and Amazon DynamoDB Update Sample Event (p. 23). For general format, see GetRecord in the Amazon
DynamoDB API Reference. For an example use case, see Using AWS Lambda with Amazon
DynamoDB (p. 151).
16
From a user perspective, Amazon SNS invokes your Lambda function asynchronously. Once a user calls
the Publish API to publish a message, Amazon SNS will queue the message and return success. From
there, Amazon SNS will pull the message from the queue and invoke the Lambda function synchronously.
Lambda then returns a delivery status.
If there is an error calling Lambda, Amazon SNS will retry invoking the Lambda function up to 50 times.
After 50 tries, if Amazon SNS still could not successfully invoke the Lambda function, then Amazon SNS
will send a delivery status failure message to CloudWatch.
Amazon Cognito
The Amazon Cognito Events feature enables you to run Lambda function in response to events in Amazon
Cognito. For example, you can invoke a Lambda function for the Sync Trigger events, that is published
each time a dataset is synchronized. To learn more and walk through an example, see Introducing Amazon
Cognito Events: Sync Triggers in the Mobile Development blog.
You configure event source mapping using Amazon Cognito event subscription configuration. For
information about event source mapping and a sample event, see Amazon Cognito Events in the Amazon
Cognito Developer Guide. For another example event, see Amazon Cognito Sync Trigger Sample
Event (p. 25)
Amazon Cognito is configured to invoke a Lambda function synchronously. AWS Lambda returns response
in real time.
AWS CloudFormation
As part of deploying AWS CloudFormation stacks, you can specify a Lambda function as a custom
resource to execute any custom commands. Associating a Lambda function with a custom resource
enables you to invoke your Lambda function whenever you create, update, or delete AWS CloudFormation
stacks.
You configure event source mapping in AWS CloudFormation using stack definition. For more information,
see AWS Lambda-backed Custom Resources in the AWS CloudFormation User Guide.
For an example event, see AWS CloudFormation Create Request Sample Event (p. 20).
AWS CloudFormation invokes your Lambda function asynchronously.
17
AWS Config
You can use AWS Lambda functions to evaluate whether your AWS resource configurations comply with
your custom Config rules. As resources are created, deleted, or changed, AWS Config records these
changes and sends the information to your Lambda functions. Your Lambda functions then evaluate the
changes and report results to AWS Config. You can then use AWS Config to assess overall resource
18
compliance: you can learn which resources are noncompliant and which configuration attributes are the
cause of noncompliance.
You maintain event source mapping in AWS Config by using a rule target definition. For more information,
see the PutConfigRule operation in the AWS Config API reference.
For more information, see Evaluating Resources With AWS Config Rules. For an example of setting a
custom rule, see Developing a Custom Rule for AWS Config. For example Lambda functions, see Example
AWS Lambda Functions for AWS Config Rules (Node.js).
AWS Config is configured to invoke a Lambda function asynchronously.
Amazon Echo
You can use Lambda functions to build services that give new skills to Alexa, the Voice assistant on
Amazon Echo. The Alexa Skills Kit provides the APIs, tools, and documentation to create these new
skills, powered by your own services running as Lambda functions. Amazon Echo users can access these
new skills by asking Alexa questions or making requests. For more information, see Getting Started with
Alexa Skills Kit.
Amazon Echo is configured to invoke a Lambda function synchronously.
19
{
"StackId": stackidarn,
"ResponseURL": "http://pre-signed-S3-url-for-response",
"ResourceProperties": {
"StackName": "stack-name",
"List": [
"1",
"2",
"3"
]
},
"RequestType": "Create",
"ResourceType": "Custom::TestResource",
"RequestId": "unique id for this create request",
"LogicalResourceId": "MyTestResource"
}
"Records": [
{
"eventVersion": "1.0",
"ses": {
"mail": {
"commonHeaders": {
"from": [
"Jane Doe <janedoe@example.com>"
],
"to": [
"johndoe@example.com"
20
],
"returnPath": "janedoe@example.com",
"messageId": "<0123456789example.com>",
"date": "Wed, 7 Oct 2015 12:34:56 -0700",
"subject": "Test Subject"
},
"source": "janedoe@example.com",
"timestamp": "1970-01-01T00:00:00.000Z",
"destination": [
"johndoe@example.com"
],
"headers": [
{
"name": "Return-Path",
"value": "<janedoe@example.com>"
},
{
"name": "Received",
"value": "from mailer.example.com (mailer.example.com [203.0.113.1])
by inbound-smtp.us-west-2.amazonaws.com with SMTP id o3vrnil0e2ic28trm7df
hrc2v0cnbeccl4nbp0g1x for johndoe@example.com; Wed, 07 Oct 2015 12:34:56
+0000 (UTC)"
},
{
"name": "DKIM-Signature",
"value": "v=1; a=rsa-sha256; c=relaxed/relaxed; d=example.com;
s=example; h=mime-version:from:date:message-id:subject:to:content-type;
bh=jX3F0bCAI7sIbkHyy3mLYO28ieDQz2R0P8HwQkklFj4x=; b=sQwJ+LMe9RjkesGu+vqU56as
vMhrLRRYrWCbVt6WJulueecwfEwRf9JVWgkBTKiL6m2hr70xDbPWDhtLdLO+jB3hzjVnX
wK3pYIOHw3vxG6NtJ6o61XSUwjEsp9tdyxQjZf2HNY
ee873832l3K1EeSXKzxYk9Pwqcpi3dMC74ct9GukjIevf1H46hm1L2d9VYTL0LGZGHOAyM
nHmEGB8ZExWbI+k6khpurTQQ4sp4PZPRlgHtnj3Zzv7nmp
To7dtPG5z5S9J+L+Ba7dixT0jn3HuhaJ9b+VThboo4YfsX9PMNhWWxGjVksSFOcG
luPO7QutCPyoY4gbxtwkN9W69HA=="
},
{
"name": "MIME-Version",
"value": "1.0"
},
{
"name": "From",
"value": "Jane Doe <janedoe@example.com>"
},
{
"name": "Date",
"value": "Wed, 7 Oct 2015 12:34:56 -0700"
},
{
"name": "Message-ID",
"value": "<0123456789example.com>"
},
{
"name": "Subject",
"value": "Test Subject"
},
{
"name": "To",
value": "johndoe@example.com"
21
},
{
"name": "Content-Type",
"value": "text/plain; charset=UTF-8"
}
],
"headersTruncated": false,
"messageId": "o3vrnil0e2ic28trm7dfhrc2v0clambda4nbp0g1x"
},
"receipt": {
"recipients": [
"johndoe@example.com"
],
"timestamp": "1970-01-01T00:00:00.000Z",
"spamVerdict": {
"status": "PASS"
},
"dkimVerdict": {
"status": "PASS"
},
"processingTimeMillis": 574,
"action": {
"type": "Lambda",
"invocationType": "Event",
"functionArn": functionarn
},
"spfVerdict": {
"status": "PASS"
},
"virusVerdict": {
"status": "PASS"
}
}
},
"eventSource": "aws:ses"
}
]
}]}
22
{
"Records": [
{
"eventID": "1",
"eventVersion": "1.0",
"dynamodb": {
"Keys": {
23
"Id": {
"N": "101"
}
},
"NewImage": {
"Message": {
"S": "New item!"
},
"Id": {
"N": "101"
}
},
"StreamViewType": "NEW_AND_OLD_IMAGES",
"SequenceNumber": "111",
"SizeBytes": 26
},
"awsRegion": "us-west-2",
"eventName": "INSERT",
"eventSourceARN": eventsourcearn,
"eventSource": "aws:dynamodb"
},
{
"eventID": "2",
"eventVersion": "1.0",
"dynamodb": {
"OldImage": {
"Message": {
"S": "New item!"
},
"Id": {
"N": "101"
}
},
"SequenceNumber": "222",
"Keys": {
"Id": {
"N": "101"
}
},
"SizeBytes": 59,
"NewImage": {
"Message": {
"S": "This item has changed"
},
"Id": {
"N": "101"
}
},
"StreamViewType": "NEW_AND_OLD_IMAGES"
},
"awsRegion": "us-west-2",
"eventName": "MODIFY",
"eventSourceARN": sourcearn,
"eventSource": "aws:dynamodb"
},
{
"eventID": "3",
"eventVersion": "1.0",
24
"dynamodb": {
"Keys": {
"Id": {
"N": "101"
}
},
"SizeBytes": 38,
"SequenceNumber": "333",
"OldImage": {
"Message": {
"S": "This item has changed"
},
"Id": {
"N": "101"
}
},
"StreamViewType": "NEW_AND_OLD_IMAGES"
},
"awsRegion": "us-west-2",
"eventName": "REMOVE",
"eventSourceARN": sourcearn,
"eventSource": "aws:dynamodb"
}
]
}
{
"datasetName": "datasetName",
"eventType": "SyncTrigger",
"region": "us-east-1",
"identityId": "identityId",
"datasetRecords": {
"SampleKey2": {
"newValue": "newValue2",
"oldValue": "oldValue2",
"op": "replace"
},
"SampleKey1": {
"newValue": "newValue1",
"oldValue": "oldValue1",
"op": "replace"
}
},
"identityPoolId": "identityPoolId",
"version": 2
}
25
"Records": [
{
"eventID": "shardId000000000000:49545115243490985018280067714973144582180062593244200961",
"eventVersion": "1.0",
"kinesis": {
"partitionKey": "partitionKey-3",
"data": "SGVsbG8sIHRoaXMgaXMgYSB0ZXN0IDEyMy4=",
"kinesisSchemaVersion": "1.0",
"sequenceNumber":
"49545115243490985018280067714973144582180062593244200961"
},
"invokeIdentityArn": identityarn,
"eventName": "aws:kinesis:record",
"eventSourceARN": eventsourcearn,
"eventSource": "aws:kinesis",
"awsRegion": "us-east-1"
}
]
}
"Records": [
{
"eventVersion": "2.0",
"eventTime": "1970-01-01T00:00:00.000Z",
"requestParameters": {
"sourceIPAddress": "127.0.0.1"
},
"s3": {
"configurationId": "testConfigRule",
"object": {
"eTag": "0123456789abcdef0123456789abcdef",
"sequencer": "0A1B2C3D4E5F678901",
"key": "HappyFace.jpg",
"size": 1024
},
"bucket": {
"arn": bucketarn,
"name": "sourcebucket",
"ownerIdentity": {
"principalId": "EXAMPLE"
}
},
"s3SchemaVersion": "1.0"
},
"responseElements": {
"x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqr
stuvwxyzABCDEFGH",
"x-amz-request-id": "EXAMPLE123456789"
26
},
"awsRegion": "us-east-1",
"eventName": "ObjectCreated:Put",
"userIdentity": {
"principalId": "EXAMPLE"
},
"eventSource": "aws:s3"
}
]
}
{
"Records": [
{
"eventVersion": "2.0",
"eventTime": "1970-01-01T00:00:00.000Z",
"requestParameters": {
"sourceIPAddress": "127.0.0.1"
},
"s3": {
"configurationId": "testConfigRule",
"object": {
"sequencer": "0A1B2C3D4E5F678901",
"key": "HappyFace.jpg"
},
"bucket": {
"arn": bucketarn,
"name": "sourcebucket",
"ownerIdentity": {
"principalId": "EXAMPLE"
}
},
"s3SchemaVersion": "1.0"
},
"responseElements": {
"x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqr
stuvwxyzABCDEFGH",
"x-amz-request-id": "EXAMPLE123456789"
},
"awsRegion": "us-east-1",
"eventName": "ObjectRemoved:Delete",
"userIdentity": {
"principalId": "EXAMPLE"
},
"eventSource": "aws:s3"
}
]
}
27
{
"operation": "echo",
"message": "Hello world!"
}
For example, consider a Lambda function that processes Amazon S3 events. Suppose that the Lambda
function takes on average three seconds and Amazon S3 publishes 10 events per second. Then, you
will have 30 concurrent executions of your Lambda function.
Request Rate
Request rate refers to the rate at which your Lambda function is invoked. For all services except the
stream-based services, the request rate is the rate at which the event sources generate the events. For
stream-based services, AWS Lambda calculates the request rate as follow:
request rate = number of concurrent executions / function duration
For example, if there are five active shards on a stream (that is, you have five Lambda functions running
in parallel) and your Lambda function takes about two seconds, the request rate is 2.5 requests/second.
Safety Limit
By default, AWS Lambda limits the total concurrent executions across all functions within a given region
to 100. The default limit is a safety limit that protects you from costs due to potential runaway or recursive
functions during initial development and testing. To increase this limit above the default, follow the steps
in To request a limit increase for concurrent executions (p. 29).
28
Any invocation that causes your function's concurrent execution to exceed the safety limit is throttled,
and does not execute your function. Each throttled invocation increases the CloudWatch Throttles
metric for the function.
The throttled invocation is handled differently based on how the function is invoked:
Event sources that aren't stream-based Some of these event sources invoke a Lambda function
synchronously and others invoke it asynchronously.
Synchronous invocation If the function is invoked synchronously and is throttled, the invoking
application receives a 429 error and the invoking application is responsible for retries. These event
sources may have additional retries built into the integration. For example, CloudWatch Logs retries
the failed batch up to five times with delays between retries. For a list of supported event sources
and the invocation types that they use, see Supported Event Sources (p. 15).
If you invoke Lambda through API Gateway, you need to make sure you map Lambda response
errors to API Gateway error codes. If you invoke the function directly, such as through the AWS
SDKs using the RequestResponse invocation mode or through API Gateway, your client receives
the 429 error and you can choose to retry the invocation.
Stream-based event sources For stream-based event sources (Amazon Kinesis Streams and
DynamoDB streams), AWS Lambda polls your stream and invokes your Lambda function. Therefore,
when your Lambda function is throttled, AWS Lambda attempts to process the throttled batch of records
until the time the data expires, which can be up to seven days for Amazon Kinesis Streams. The throttled
request is treated as blocking per shard and Lambda will not read any new records from the shard until
the throttled batch of records either expires or succeeds. If there is more than one shard in the stream,
Lambda will continue invokes on the non-throttled shards until one gets through.
Open the AWS Support Center page, sign in, if necessary, and then click Create case.
Under Regarding, select Service Limit Increase.
3.
Under Limit Type, select Lambda, fill in the necessary fields in the form, and then click the button
at the bottom of the page for your preferred method of contact.
Note
AWS may automatically raise the concurrent execution limit on your behalf to enable your function
to match the incoming event rate, as in the case of triggering the function from an Amazon S3
bucket.
Suggested Reading
If you are new to AWS Lambda, we suggest you read through all of the topics in the How It Works section
to familiarize yourself with Lambda. The next topic is Retries on Errors (p. 30).
After you read all of the topics in the How it Works section, we recommend that you review Building AWS
Lambda-Based Applications (p. 47), try the Getting Started (p. 35) exercise, and then explore the Use
Cases (p. 125). Each use case provides step-by-step instructions for you to set up the end-to-end
experience.
29
Retries on Errors
A Lambda function can fail for any of the following reasons:
The function times out while trying to reach an endpoint.
The function experiences resource constraints, such as out-of-memory errors or other timeouts.
If any of these failures occur, your function will throw an exception. How the exception is handled depends
upon how the Lambda function was invoked:
Event sources that aren't stream-based Some of these event sources are set up to invoke a
Lambda function synchronously and others invoke it asynchronously. Accordingly, exceptions are
handled as follows:
Synchronous invocation The invoking application receives a 429 error, and is responsible for
retries. For a list of supported event sources and the invocation types they use, see Supported Event
Sources. These event sources may have additional retries built into the integration.
If you invoked the Lambda function directly through AWS SDKs, or through API Gateway, your client
receives the error and can choose to retry. If you are invoking Lambda through API Gateway, you
need to make sure you map Lambda response errors to API Gateway error codes.
Asynchronous invocation AWS Lambda automatically retries the failed event up to three times
with delays between retries. Asynchronous events are queued before being used to invoke the
Lambda function.
Stream-based event sources For stream-based event sources (Amazon Kinesis Streams and
DynamoDB streams), AWS Lambda polls your stream and invokes your Lambda function. Therefore,
if a Lambda function fails, AWS Lambda attempts to process the erring batch of records until the time
the data expires, which can be up to seven days for Amazon Kinesis Streams. The exception is treated
as blocking, and AWS Lambda will not read any new records from the stream until the failed batch of
records either expires or processed successfully.This ensures that AWS Lambda processes the stream
events in order.
For more information about invocation modes, see Event Source Mapping (p. 10).
Suggested Reading
If you are new to AWS Lambda, we suggest you read through all of the topics in the How It Works section
to familiarize yourself with Lambda. The next topic is AWS Lambda Permissions Model (p. 31).
After you read all of the topics in the How it Works section, we recommend that you review Building AWS
Lambda-Based Applications (p. 47), try the Getting Started (p. 35) exercise, and then explore the Use
Cases (p. 125). Each use case provides step-by-step instructions for you to set up the end-to-end
experience.
30
For stream-based event sources (Amazon Kinesis Streams and DynamoDB streams), AWS Lambda
polls the streams on your behalf and reads new records on the stream, so you need to grant AWS
Lambda permissions for the relevant stream actions.
When your Lambda function executes, it can access AWS resources in your account (for example,
read an object from your S3 bucket). AWS Lambda executes your Lambda function on your behalf by
assuming the role you provided at the time of creating the Lambda function. Therefore, you need to
grant the role the necessary permissions that your Lambda function needs, such as permissions for
Amazon S3 actions to read an object.
The following sections describe permissions management.
Topics
Manage Permissions: Using an IAM Role (Execution Role) (p. 31)
Manage Permissions: Using a Lambda Function Policy (p. 32)
If the event source is stream-based (Amazon Kinesis Streams and DynamoDB streams), AWS Lambda
polls these streams on your behalf. AWS Lambda needs permissions to poll the stream and read new
records on the stream so you need to grant the relevant permissions to this role.
For more information about IAM roles, see Roles (Delegation and Federation) in the IAM User Guide.
Important
The user that creates the IAM role is, in effect, passing permissions to AWS Lambda to assume
this role, which requires the user to have permissions for the iam:PassRole action. If an
administrator user is creating this role, you don't need to do anything extra to set up permissions
for the iam:PassRole action because the administrator user has full permissions, including the
iam:PassRole action.
31
To simplify the process for creating an execution role, AWS Lambda provides the following AWS managed
(predefined) permissions policies that you can use. These policies include common permissions for
specific scenarios:
AWSLambdaBasicExecutionRole Grants permissions only for the Amazon CloudWatch Logs
actions to write logs. You can use this policy if your Lambda function does not access any other AWS
resources except writing logs.
32
Note
Instead of using a Lambda function policy, you can create another IAM role that grants the event
sources (for example, Amazon S3 or DynamoDB) permissions to invoke your Lambda function.
However, you might find that resource policies are easier to set up and they make it easier for
you to track which event sources have permissions to invoke your Lambda function.
For more information about Lambda function policies, see Using Resource-Based Policies for AWS
Lambda (Lambda Function Policies) (p. 259). For more information about Lambda permissions, see
Authentication and Access Control for AWS Lambda (p. 240).
Suggested Reading
If you are new to AWS Lambda, we suggest you read through all of the topics in the How It Works section
to familiarize yourself with Lambda. The next topic is Lambda Execution Environment and Available
Libraries (p. 33).
After you read all of the topics in the How it Works section, we recommend that you review Building AWS
Lambda-Based Applications (p. 47), try the Getting Started (p. 35) exercise, and then explore the Use
Cases (p. 125). Each use case provides step-by-step instructions for you to set up the end-to-end
experience.
33
If you are using any native binaries in your code, make sure they are compiled in this environment.
AWS Lambda supports the following runtime versions:
Node.js v0.10.36, v4.3.2 (recommended)
Java Java 8
Python Python 2.7
The following libraries are available in the AWS Lambda execution environment so you don't need to
include them:
ImageMagick Installed with default settings. For versioning information, see imagemagick nodejs
wrapper and ImageMagick native binary (search for "ImageMagick").
AWS SDK AWS SDK for JavaScript version 2.4.9
If you author your Lambda function code in Python, the following libraries are available in the AWS Lambda
execution environment so you don't need to include them:
AWS SDK for Python (Boto 3) version 1.3.0, Botocore version 1.4.9
There are no additional libraries available for Java.
Suggested Reading
If you are new to AWS Lambda, we suggest you read through all of the topics in the How It Works section
to familiarize yourself with Lambda, starting with How It Works (p. 3).
After you read all of the topics in the How it Works section, we recommend that you review Building AWS
Lambda-Based Applications (p. 47), try the Getting Started (p. 35) exercise, and then explore the Use
Cases (p. 125). Each use case provides step-by-step instructions for you to set up the end-to-end
experience.
34
Getting Started
In this Getting Started section, you do the following:
Set up an AWS account and AWS Command Line Interface (AWS CLI). Most tutorials use the AWS
CLI commands.
Create and test a simple Hello World Lambda function.
To get started, complete the steps in the following topics:
Topics
Step 1: Set Up an AWS Account and the AWS CLI (p. 35)
Step 2: Create a HelloWorld Lambda Function and Explore the Console (p. 39)
35
Note your AWS account ID, because you'll need it for the next task.
36
To create an IAM user for yourself, add the user to the administrators group, and create
a password for the user
1.
In the navigation pane, choose Users, and then choose Create New Users.
2.
3.
4.
5.
Choose Create.
In the list of users, choose the name (not the check box) of the user you just created. You can use
the Search box to search for the user name.
Choose the Groups tab and then choose Add User to Groups.
6.
7.
8.
9.
Select the check box next to the administrators group. Then choose Add to Groups.
Choose the Security Credentials tab. Under Sign-In Credentials, choose Manage Password.
Select Assign a custom password. Then type a password in the Password and Confirm Password
boxes. When you are finished, choose Apply.
3.
The aws_account_number is your AWS account ID without hyphen. For example, if your AWS
account ID is 1234-5678-9012, your AWS account number is 123456789012. For information
about how to find your account number, see Your AWS Account ID and Its Alias in the IAM User
Guide.
Enter the IAM user name and password that you just created. When you're signed in, the navigation
bar displays your_user_name @ your_aws_account_id.
If you don't want the URL for your sign-in page to contain your AWS account ID, you can create an account
alias.
To sign in after you create an account alias, use the following URL:
https://your_account_alias.signin.aws.amazon.com/console/
To verify the sign-in link for IAM users for your account, open the IAM console and check under IAM
users sign-in link: on the dashboard.
For more information about IAM, see the following:
37
Next Step
Step 1.2: Set Up the AWS Command Line Interface (AWS CLI) (p. 38)
Download and configure the AWS CLI. For instructions, see the following topics in the AWS Command
Line Interface User Guide.
Getting Set Up with the AWS Command Line Interface
Configuring the AWS Command Line Interface
2.
Add a named profile for the administrator user in the AWS CLI config file. You use this profile when
executing the AWS CLI commands.
[profile adminuser]
aws_access_key_id = adminuser access key ID
aws_secret_access_key = adminuser secret access key
region = aws-region
3.
For a list of available AWS regions, see Regions and Endpoints in the Amazon Web Services General
Reference.
Verify the setup by entering the following commands at the command prompt.
Try the help command to verify that the AWS CLI is installed on your computer:
aws help
Try a Lambda command to verify the user can reach AWS Lambda. This command lists Lambda
functions in the account, if any. The AWS CLI uses the adminuser credentials to authenticate
the request.
aws lambda list-functions --profile adminuser
Now that you have set up an account and AWS CLI, you can create your first Lambda function. For
instructions, see Step 2: Create a HelloWorld Lambda Function and Explore the Console (p. 39).
38
39
Sign in to the AWS Management Console and open the AWS Lambda console.
2.
Note
The console shows the Get Started Now page only if you do not have any Lambda functions
created. If you have created functions already, you will see the Lambda > Functions page.
On the list page, choose Create a Lambda function to go to the Lambda > New function
page.
3.
On the Select blueprint page, first explore the available blueprints. Then, select a specific blueprint
for this Getting Started exercise.
a.
Review the blueprints.You can also use the Filter to search for specific blueprints. For example:
Enter S3 in Filter to get only the list of blueprints available to process Amazon S3 events.
Enter dynamodb in Filter to get a list of available blueprints to process Amazon DynamoDB
events.
b.
4.
For this Getting Started exercise, enter hello-world-python in Filter, and then choose the
hello-world-python blueprint.
On the Configure triggers page, you can optionally choose a service that automatically triggers
your Lambda function by choosing the gray box with ellipses (...) to display a list of available services.
a.
Depending on which service you select, you are prompted to provide relevant information for
that service. For example, if you select DynamoDB, you need to provide the following:
The name of the DynamoDB table
Batch size
Starting position
b.
5.
For this Getting Started exercise, do not configure a trigger and choose Next.
40
Code authored in Python is provided. It reads incoming event data and logs some of the
information to CloudWatch.
Handler shows lambda_function.lambda_handler value. It is the
filename.handler-function. The console saves the sample code in the
lambda_function.py file and in the code lambda_handler is the function name that
receives the event as a parameter when the Lambda function is invoked. For more information,
see Lambda Function Handler (Python) (p. 82).
b.
c.
After creating the Lambda function, you invoke it using sample events of this form in the
next section.
d.
ii.
iii.
iv.
Note
Optionally, you could select Choose an existing role if you already have a role created
with specific permissions beyond basic execution.You can also select Create a custom
role. When you choose this option, a window appears where you can edit the
permissions policy inline.
e.
In the Advanced settings section, leave the default Lambda function configuration values.
f.
g.
The memory and timeout values are sufficient for the Lambda function you are creating. These
configurations influence the performance of your code. For more information, see Lambda
Function (p. 8).
Choose Next.
Choose Create Function to create a Lambda function.
41
The console saves the code into a file and then zips the file, which is the deployment package.
The console then uploads the deployment package to AWS Lambda creating your Lambda
function. The console shows the hello-world-python Lambda function, you can now perform
various action including test the function:
Next Step
Step 2.2: Invoke the Lambda Function Manually and Verify Results, Logs, and Metrics (p. 42)
42
{
"key3": "value3",
"key2": "value2",
"key1": "value1"
}
You can change key and values in the sample JSON, but don't change the event structure. If you
do change any keys and values, you must update the sample code accordingly. Choose Save and
test.
3.
AWS Lambda executes your function on your behalf. The handler in your Lambda function receives
and then processes the sample event.
4.
Note
The console always uses the RequestResponse invocation type (synchronous invocation)
when invoking a Lambda function which causes AWS Lambda to return a response
immediately. For more information, see Invocation Types (p. 9).
The Summary section shows the key information reported in the Log output section (the REPORT
line in the execution log).
The Log output section shows the log AWS Lambda generates for each execution. These are
the logs written to CloudWatch by the Lambda function. The AWS Lambda console shows these
logs for your convenience.
5.
6.
Note that the Click here link shows logs in the CloudWatch console. The function then adds logs to
Amazon CloudWatch in the log group that corresponds to the Lambda function.
Run the Lambda function a few times to gather some metrics that you can view in the next step.
Choose the Monitoring tab to view the CloudWatch metrics for your Lambda function. This page
shows four CloudWatch metrics.
43
Next Step
Step 2.3: (Optional) Try Other Blueprints (p. 44)
44
The Lambda console provide blueprint to set up an example Lambda function to process Amazon S3
events. When creating a Lambda function in the console on the Select blueprint page, enter s3 in the
Filter box to search for a list of available blueprints.
For more information about working with different event sources, see Use Cases (p. 125).
Next Step
Step 2.4: (Optional) Create a Lambda Function Authored in Java (p. 45)
The programming model explains how to write your Java code in detail, for example the input/output
types AWS Lambda supports. For more information about the programming model, see Programming
Model for Authoring Lambda Functions in Java (p. 63). For now, note the following about this code:
When you package and upload this code to create your Lambda function, you specify the
example.Hello::myHandler method reference as the handler.
The handler in this example uses the int type for input and the String type for output.
AWS Lambda supports input/output of JSON-serializable types and InputStream/OutputStream types.
When you invoke this function you will pass a sample int (for example, 123).
In this exercise you use the console to manually invoke this Lambda function. The console always uses
the RequestResponse invocation type (synchronous) and therefore you will see the response in the
console.
The handler includes the optional Context parameter. In the code we use the LambdaLogger provided
by the Context object to write log entries to CloudWatch logs. For information about using the Context
object, see The Context Object (Java) (p. 74).
45
First, you need to package this code and any dependencies into a deployment package. Then, you can
use the Getting Started exercise to upload the package to create your Lambda function and test using
the console.
Next Step
What's Next? (p. 46)
What's Next?
This Getting Started exercise provided you with an overview of how to use the AWS Lambda console.
You used the hello-world-python blueprint to create a simple Lambda function that you invoked manually
using sample event data.
AWS Lambda functions can also be automatically invoked in response to events in other AWS services
such as Amazon S3 and DynamoDB. Lambda functions can also be invoked on-demand over HTTPS.
You can also build your own custom event sources and invoke Lambda functions on demand. For more
information, see How It Works (p. 3).
Depending on your integration scenario, whether your application needs event-driven Lambda function
invocation or on-demand invocation, see the following sections:
The console provides several blueprints for you to set up example Lambda functions quickly that can
process events from these event sources. You may want to explore other blueprints in the console to get
started with Lambda functions triggered by these event sources.
46
Uploading code and creating Lambda functions How do I upload my code package to AWS
Lambda? How do I tell AWS Lambda where to begin executing my code? How do I specify compute
requirements like memory and timeout?
Monitoring and troubleshooting For my Lambda function that is in production, what metrics are
available? If there are any failures, how do I get logs or troubleshoot issues?
The following sections provide introductory information and the Example section at the end provides
working examples for you to explore.
Note
This topic provides an introductory overview of how you develop AWS Lambda-based applications.
The How It Works (p. 3) section describes the specifics about Lambda functions, event sources,
and how AWS Lambda executes your Lambda functions.
47
Node.js
You can use the console if the languages you choose do not require compilation, the code is saved in a single file,
and it does not depend on any libraries.
Java
The AWS Toolkit also creates the deployment package, which is explained in
Deploying Code and Creating a Lambda
Function (p. 48).
Python
You can use the console if the languages you choose do not require compilation, the code is saved in a single file,
and it does not depend on any libraries.
In addition, regardless of the language you choose, there is a pattern to writing Lambda function code.
For example, how you write the handler method of your Lambda function (that is, the method that AWS
Lambda first calls when it begins executing the code), how you pass events to the handler, what statements
you can use in your code to generate logs in CloudWatch Logs, how to interact with AWS Lambda runtime
and obtain information such as the time remaining before timeout, and how to handle exceptions. The
Programming Model (p. 51) section provides information for each of the supported languages.
Note
After you familiarize yourself with AWS Lambda, see the Use Cases (p. 125), which provide
step-by-step instructions to help you explore the end-to-end experience.
48
Topics
Creating a Deployment Package (p. 49)
Uploading a Deployment Package (p. 49)
Testing a Lambda Function (p. 49)
Using AWS CloudFormation (p. 50)
Note
This section provides an introductory overview of developing AWS Lambda-based applications.
How It Works (p. 3) describes specifics about Lambda functions, event sources, and how AWS
Lambda executes your Lambda functions.
49
Use Cases (p. 125) If you cannot author your code using the console, you must create your own
deployment packages and use the AWS CLI (or SDKs) to create your Lambda function. For more
information, see Authoring Code for Your Lambda Function (p. 48). Most examples in the Uses Cases
section use the AWS CLI. If you are new to AWS Lambda, we recommend that you try one of these
exercises.
Related Topics
The following topics provide additional information.
Programming Model (p. 51)
Creating a Deployment Package (p. 89)
AWS Lambda Function Versioning and Aliases (p. 101)
Troubleshooting and Monitoring AWS Lambda Functions with Amazon CloudWatch (p. 118)
50
Programming Model
You write code for your Lambda function in one of the languages AWS Lambda supports. Regardless of
the language you choose, there is a common pattern to writing code for a Lambda function that includes
the following core concepts:
Handler Handler is the function AWS Lambda calls to start execution of your Lambda function. You
identify the handler when you create your Lambda function. When a Lambda function is invoked, AWS
Lambda starts executing your code by calling the handler function. AWS Lambda passes any event
data to this handler as the first parameter. Your handler should process the incoming event data and
may invoke any other functions/methods in your code.
The context object and how it interacts with Lambda at runtime AWS Lambda also passes a
context object to the handler function, as the second parameter. Via this context object your code can
interact with AWS Lambda. For example, your code can find the execution time remaining before AWS
Lambda terminates your Lambda function.
In addition, for languages such as Node.js, there is an asynchronous platform that uses callbacks.
AWS Lambda provides additional methods on this context object.You use these context object methods
to tell AWS Lambda to terminate your Lambda function and optionally return values to the caller.
Logging Your Lambda function can contain logging statements. AWS Lambda writes these logs to
CloudWatch Logs. Specific language statements generate log entries, depending on the language you
use to author your Lambda function code.
Exceptions Your Lambda function needs to communicate the result of the function execution to AWS
Lambda. Depending on the language you author your Lambda function code, there are different ways
to end a request successfully or to notify AWS Lambda an error occurred during execution. If you invoke
the function synchronously, then AWS Lambda forwards the result back to the client.
Note
Your Lambda function code must be written in a stateless style, and have no affinity with the
underlying compute infrastructure. Your code should expect local file system access, child
processes, and similar artifacts to be limited to the lifetime of the request. Persistent state should
be stored in Amazon S3, Amazon DynamoDB, or another cloud storage service. Requiring
functions to be stateless enables AWS Lambda to launch as many copies of a function as needed
to scale to the incoming rate of events and requests. These functions may not always run on
the same compute instance from request to request, and a given instance of your Lambda
function may be used more than once by AWS Lambda.
The following language specific topics provide detail information:
Programming Model (Node.js) (p. 51)
Programming Model for Authoring Lambda Functions in Java (p. 63)
Programming Model for Authoring Lambda Functions in Python (p. 81)
51
Important
The v0.10.42 runtime will be unavailable to create new functions beginning on October 2016,
given the end-of-life announcement for this version. We recommend that you use v4.3. All
examples in this documentation use the new v4.3 runtime. For information about programming
model differences in the v0.10.42 runtime, see Using the Earlier Node.js Runtime
v0.10.42 (p. 60).
When you create a Lambda function, you specify the runtime that you want to use. For more information,
see runtime parameter of the CreateFunction (p. 283).
The following sections explain how common programming patterns and core concepts apply when
authoring Lambda function code in Node.js. The programming model described in the following sections
apply to both versions, except where indicated.
Topics
Lambda Function Handler (Node.js) (p. 52)
The Context Object (Node.js) (p. 55)
Logging (Node.js) (p. 57)
Exceptions (Node.js) (p. 59)
Using the Earlier Node.js Runtime v0.10.42 (p. 60)
The callback parameter is optional and you want to return information to the caller.
exports.myHandler = function(event, context, callback) {
...
// Use callback() and return information to the caller.
}
Note
The callback is supported only in the Node.js runtime v4.3. If you are using the earlier runtime
v0.10.42, you need to use the context methods (done, succeed, and fail) to properly terminate
52
the Lambda function. For information about terminating Lambda functions written for earlier
runtime versions, see Using the Earlier Node.js Runtime v0.10.42 (p. 60).
myHandler This is the name of the function AWS Lambda invokes. You export this so it is visible to
AWS Lambda. Suppose you save this code as helloworld.js. Then, helloworld.myHandler is
the handler. For more information, see handler in CreateFunction (p. 283).
If you used the RequestResponse invocation type (synchronous execution), AWS Lambda returns
the result of the Node.js function call to the client invoking the Lambda function (in the HTTP response
to the invocation request, serialized into JSON). For example, AWS Lambda console uses
the RequestResponse invocation type, so when you test invoke the function using the console, the
console will display the return value.
If the handler does not return anything, AWS Lambda returns null.
If you used the Event invocation type (asynchronous execution), the value is discarded.
Example
Consider the following Node.js example code.
exports.myHandler = function(event, context, callback) {
console.log("value1 = " + event.key1);
console.log("value2 = " + event.key2);
callback(null, "some success message");
// or
// callback("some error type");
}
This example has one function, which is also the handler. In the function, the console.log() statements
log some of the incoming event data to CloudWatch Logs. When the callback is called, the Lambda
function exits only after the Node.js event loop is empty (the Node.js event loop is not the same as the
event that was passed as a parameter).
Note
If you are using the earlier runtime v0.10.42, you need to use the context methods (done, succeed,
and fail) to properly terminate the Lambda function. For more information, see Using the Earlier
Node.js Runtime v0.10.42 (p. 60).
2.
3.
For instructions to create a Lambda function using the console, see Step 2.1: Create a Hello World
Lambda Function (p. 39).
Replace the template code with the code provided in this section and create the function.
Test the Lambda function using the Sample event template called Hello World provided in the
Lambda console. For instructions on how to do this, see Step 2.2: Invoke the Lambda Function
Manually and Verify Results, Logs, and Metrics (p. 42).
53
Where:
error is an optional parameter that you can use to provide results of the failed Lambda function
execution. When a Lambda function succeeds, you can pass null as the first parameter.
result is an optional parameter that you can use to provide the result of a successful function
execution. The result provided must be JSON.stringify compatible. If an error is provided, this
parameter is ignored.
Note
Using the callback parameter is optional. If you don't use the optional callback parameter,
the behavior is same as if you called the callback() without any parameters. You can specify
the callback in your code to return information to the caller.
If you don't use callback in your code, AWS Lambda will call it implicitly and the return value is null.
When the callback is called (explicitly or implicitly), AWS Lambda continues the Lambda function invocation
until the Node.js event loop is empty.
The following are example callbacks:
callback();
// Indicates success but no information returned to the caller.
callback(null); // Indicates success but no information returned to the caller.
callback(null, "success"); // Indicates success with information returned to
the caller.
callback(error);
// Indicates error with error information returned to the
caller.
AWS Lambda treats any non-null value for the error parameter as a handled exception.
Note the following:
Regardless of the invocation type specified at the time of the Lambda function invocation (see
Invoke (p. 304)), the callback method automatically logs the string representation of non-null values of
error to the Amazon CloudWatch Logs stream associated with the Lambda function.
If the Lambda function was invoked synchronously (using the RequestResponse invocation type), the
callback returns a response body as follows:
If error is null, the response body is set to the string representation of result.
If the error is not null, the error value will be populated in the response body.
Note
When the callback(error, null) (and callback(error)) is called, Lambda will log the
first 256 KB of the error object. For a larger error object, AWS Lambda truncates the log and
displays the text Truncated by Lambda next to the error object.
54
Example
Consider the following Node.js example. The handler receives runtime information via a context
parameter.
console.log('Loading function');
exports.handler = function(event, context, callback) {
//console.log('Received event:', JSON.stringify(event, null, 2));
console.log('value1 =', event.key1);
console.log('value2 =', event.key2);
console.log('value3 =', event.key3);
console.log('remaining time =', context.getRemainingTimeInMillis());
console.log('functionName =', context.functionName);
console.log('AWSrequestID =', context.awsRequestId);
console.log('logGroupName =', context.logGroupName);
console.log('logStreamName =', context.logStreamName);
console.log('clientContext =', context.clientContext);
if (typeof context.identity !== 'undefined') {
console.log('Cognito
identity ID =', context.identity.cognitoIdentityId);
}
callback(null, event.key1); // Echo back the first key value
// or
// callback("some error type");
};
The handler code in this example logs some of the runtime information of the Lambda function to
CloudWatch. If you invoke the function using the Lambda console, the console displays the logs in the
Log output section. You can create a Lambda function using this code and test it using the console.
In the console, create a Lambda function using the hello-world blueprint. In runtime, choose
nodejs4.3. For instructions on how to do this, see Step 2.1: Create a Hello World Lambda
Function (p. 39).
55
2.
Test the function, and then you can also update the code to get more context information.
context.getRemainingTimeInMillis()
Returns the approximate remaining execution time (before timeout occurs) of the Lambda function that
is currently executing. The timeout is one of the Lambda function configuration. When the timeout reaches,
AWS Lambda terminates your Lambda function.
You can use this method to check the remaining time during your function execution and take appropriate
corrective action at run time.
The general syntax is:
context.getRemainingTimeInMillis();
Note
If AWS Lambda retries the invocation (for example, in a situation where the Lambda function
that is processing Amazon Kinesis records throws an exception), the request ID remains
the same.
56
logGroupName
The name of the CloudWatch log group where you can find logs written by your Lambda function.
logStreamName
The name of the CloudWatch log group where you can find logs written by your Lambda function.
The log stream may or may not change for each invocation of the Lambda function.
The value is null if your Lambda function is unable to create a log stream, which can happen if the
execution role that grants necessary permissions to the Lambda function does not include permissions
for the CloudWatch actions.
identity
Information about the Amazon Cognito identity provider when invoked through the AWS Mobile SDK.
It can be null.
identity.cognitoIdentityId
identity.cognitoIdentityPoolId
For more information about the exact values for a specific mobile platform, see Identity Context in
the AWS Mobile SDK for iOS Developer Guide, and Identity Context in the AWS Mobile SDK for
Android Developer Guide.
clientContext
Information about the client application and device when invoked through the AWS Mobile SDK. It
can be null. Using clientContext, you can get the following information:
clientContext.client.installation_id
clientContext.client.app_title
clientContext.client.app_version_name
clientContext.client.app_version_code
clientContext.client.app_package_name
clientContext.Custom
For more information about the exact values for a specific mobile platform, see Client Context in the AWS
Mobile SDK for iOS Developer Guide, and Client Context in the AWS Mobile SDK for Android Developer
Guide.
Logging (Node.js)
Your Lambda function can contain logging statements. AWS Lambda writes these logs to CloudWatch.
If you use the Lambda console to invoke your Lambda function, the console displays the same logs.
The following Node.js statements generate log entries:
console.log()
console.error()
console.warn()
console.info()
57
The screenshot shows an example Log output section in Lambda console, you can also find these logs
in CloudWatch. For more information, see Accessing Amazon CloudWatch Logs for AWS Lambda (p. 122).
The console uses the RequestResponse invocation type (synchronous invocation) when invoking the
function, therefore it gets the return value (value1) back from AWS Lambda which the console displays.
2.
In the console, create a Lambda function using the hello-world blueprint. Make sure to select the
Node.js as the runtime. For instructions on how to do this, see Step 2.1: Create a Hello World
Lambda Function (p. 39).
Test the Lambda function using the Sample event template called Hello World provided in the
Lambda console. For instructions on how to do this, see Step 2.2: Invoke the Lambda Function
Manually and Verify Results, Logs, and Metrics (p. 42). You can also update the code and try other
logging methods and properties discussed in this section.
Finding Logs
You can find the logs that your Lambda function writes, as follows:
In the AWS Lambda console The Log output section in the AWS Lambda console shows the
logs.
In the response header, when you invoke a Lambda function programmatically If you invoke a
Lambda function programmatically, you can add the LogType parameter to retrieve the last 4 KB of
58
log data that is written to CloudWatch Logs. AWS Lambda returns this log information in
the x-amz-log-results header in the response. For more information, see Invoke.
If you use AWS CLI to invoke the function, you can specify the --log-type parameter with
value Tail to retrieve the same information.
In CloudWatch Logs To find your logs in CloudWatch you need to know the log group name and
log stream name. You can get that information by adding the context.logGroupName, and
context.logStreamName methods in your code. When you run your Lambda function, the resulting
logs in the console or CLI will show you the log group name and log stream name.
Exceptions (Node.js)
If your Lambda function notifies AWS Lambda that it failed to execute properly by calling the
context.fail method, AWS Lambda serializes the error information and returns it. If the error value
passed to context.fail is an exception, Lambda will attempt to serialize information about the exception
such as its type, error message, and stack trace. Otherwise, Lambda will attempt to convert the error
object to a String. Consider the following example:
console.log('Loading function');
exports.handler = function(event, context, callback) {
// This example code only throws error.
var error = new Error("something is wrong");
callback(error);
};
When you invoke this Lambda function, it will notify AWS Lambda that function execution completed with
an error and passes error information to AWS Lambda. AWS Lambda returns the error information back
to the client:
{
"errorMessage": "something is wrong",
"errorType": "Error",
"stackTrace": [
"exports.handler (/var/task/index.js:10:17)"
]
}
Note that the stack trace is returned as the stackTrace JSON array of stack trace elements.
How you get the error information back depends on the invocation type that the client specifies at the
time of function invocation:
If a client specifies the RequestResponse invocation type (that is, synchronous execution), it returns
the result to the client that made the invoke call.
For example, the console always use the RequestResponse invocation type, so the console will
display the error in the Execution result section as shown:
59
The same information is also sent to CloudWatch and the Log output section shows the same logs.
If a client specifies the Event invocation type (that is, asynchronous execution), AWS Lambda will
not return anything. Instead, it logs the error information to CloudWatch Logs. You can also see the
error metrics in CloudWatch Metrics.
Depending on the event source, AWS Lambda may retry the failed Lambda function. For example, if
Amazon Kinesis is the event source, AWS Lambda will retry the failed invocation until the Lambda function
succeeds or the records in the stream expire. For more information on retries, see Retries on Errors (p. 30).
2.
3.
In the console, create a Lambda function using the hello-world blueprint. In runtime, choose Node.js
and, in Role, choose Basic execution role. For instructions on how to do this, see Step 2.1: Create
a Hello World Lambda Function (p. 39).
Replace the template code with the code provided in this section.
Test the Lambda function using the Sample event template called Hello World provided in the
Lambda console. For instructions on how to do this, see Step 2.2: Invoke the Lambda Function
Manually and Verify Results, Logs, and Metrics (p. 42).
60
context.succeed()
Indicates the Lambda function execution and all callbacks completed successfully. Here's the general
syntax:
context.succeed(Object result);
Where:
result is an optional parameter and it can be used to provide the result of the function execution.
The result provided must be JSON.stringify compatible. If AWS Lambda fails to stringify or encounters
another error, an unhandled exception is thrown, with the X-Amz-Function-Error response header
set to Unhandled.
You can call this method without any parameters (succeed()) or pass a null value (succeed(null)).
The behavior of this method depends on the invocation type specified in the Lambda function invocation.
For more information about invocation types, see Invoke (p. 304).
If the Lambda function is invoked using the Event invocation type (asynchronous invocation), the
method will return HTTP status 202, request accepted response.
If the Lambda function is invoked using the RequestResponse invocation type (synchronous invocation),
the method will return HTTP status 200 (OK) and set the response body to the string representation
of the result.
context.fail()
Indicates the Lambda function execution and all callbacks completed unsuccessfully, resulting in a handled
exception. The general syntax is shown following:
context.fail(Error error);
Where:
error is an optional parameter that you can use to provide the result of the Lambda function execution.
If the error value is non-null, the method will set the response body to the string representation of error
and also write corresponding logs to CloudWatch. If AWS Lambda fails to stringify or encounters another
error, an unhandled error occurs with the X-Amz-Function-Error header set to Unhandled.
Note
For the error from context.fail(error) and context.done(error, null), Lambda logs
the first 256 KB of the error object. For larger error objects, AWS Lambda truncates the error
and displays the text: Truncated by Lambda next to the error object.
You can call this method without any parameters (fail()) or pass a null value (fail(null)).
61
context.done()
Causes the Lambda function execution to terminate.
Note
This method complements the succeed() and fail() methods by allowing the use of the
"error first" callback design pattern. It provides no additional functionality.
The general syntax is:
context.done(Error error, Object result);
Where:
error is an optional parameter that you can use to provide results of the failed Lambda function
execution.
result is an optional parameter that you can use to provide the result of a successful function
execution. The result provided must be JSON.stringify compatible. If an error is provided, this
parameter is ignored.
You can call this method without any parameters (done()), or pass null (done(null)).
AWS Lambda treats any non-null value for the error parameter as a handled exception.
The function behavior depends on the invocation type specified at the time of the Lambda invocation.
For more information about invocation types, see Invoke (p. 304).
Regardless of the invocation type, the method automatically logs the string representation of non-null
values of error to the Amazon CloudWatch Logs stream associated with the Lambda function.
If the Lambda function was invoked using the RequestResponse (synchronous) invocation type, the
method returns response body as follows:
If error is null, set the response body to the JSON representation of result. This is similar to
context.succeed().
If the error is not null or the function is called with a single argument of type error, the error
value will be populated in the response body.
Note
For the error from both the done(error, null) and fail(error), Lambda logs the first 256
KB of the error object, and for larger error object, AWS Lambda truncates the log and displays
the text Truncated by Lambda" next to the error object.
Note
You might need to update your Lambda code to work in the new runtime. For a list of changes
in Node.js v4.3, see API changes between v0.10 and v4 on GitHub.
If you previously created Lambda functions using Node.js runtime v0.10.42, you used one of the context
object methods (done(), succeed(), and fail()) to terminate your Lambda function. In Node.js runtime
v4.3, these methods are supported primarily for backward compatibility. We recommend you use the
callback (see Using the Callback Parameter (p. 54)). The following are callback examples equivalent
to the context object methods:
62
The following example shows the context.done() method and corresponding equivalent callback
supported in the newer runtime.
// Old way (Node.js runtime v0.10.42).
context.done(null, 'Success message');
// New way (Node.js runtime v4.3).
context.callbackWaitsForEmptyEventLoop = false;
callback(null, 'Success message');
Important
For performance reasons, AWS Lambda may reuse the same Node.js process for multiple
executions of the Lambda function. If this happens, AWS Lambda freezes the Node process
between execution,retaining the state information it needs to continue execution.
When the context methods are called, AWS Lambda freezes the Node process immediately,
without waiting for the event loop associated with the process to empty. The process state
and any events in the event loop are frozen. When the function is invoked again, if AWS
Lambda re-uses the frozen process, the function execution continues with its same global
state (for example, events that remained in the event loop will begin to get processed). However,
when you use callback, AWS Lambda continues the Lambda function execution until the event
loop is empty. After all events in the event loop are processed, AWS Lambda then freezes
the Node process, including any state variables in the Lambda function. Therefore, if you want
the same behavior as the context methods, you must set the context object property,
callbackWaitsForEmptyEventLoop, to false.
The following example shows the context.succeed() method and corresponding equivalent
callback supported in the newer runtime.
// Old way (Node.js runtime v0.10.42).
context.succeed('Success message');
// New way (Node.js runtime v4.3).
context.callbackWaitsForEmptyEventLoop = false;
callback(null, 'Success message');
The following example shows the context.fail() method and corresponding equivalent callback
supported in the newer runtime.
// Old way (Node.js runtime v0.10.42).
context.fail('Fail object');
// New way (Node.js runtime v4.3).
context.callbackWaitsForEmptyEventLoop = false;
callback('Fail object', 'Failed result');
63
In order for AWS Lambda to successfully invoke a handler it must be invoked with input data that can be
serialized into the data type of the input parameter.
In the syntax, note the following:
inputType The first handler parameter is the input to the handler, which can be event data (published
by an event source) or custom input that you provide such as a string or any custom data object. In
order for AWS Lambda to successfully invoke this handler, the function must be invoked with input
data that can be serialized into the data type of the input parameter.
outputType If you plan to invoke the Lambda function synchronously (using the RequestResponse
invocation type), you can return the output of your function using any of the supported data types. For
64
example, if you use a Lambda function as a mobile application backend, you are invoking it
synchronously. Your output data type will be serialized into JSON.
If you plan to invoke the Lambda function asynchronously (using the Event invocation type), the
outputType should be void. For example, if you use AWS Lambda with event sources such as
Amazon S3, Amazon Kinesis, and Amazon SNS, these event sources invoke the Lambda function
using the Event invocation type.
The inputType and outputType can be one of the following:
Primitive Java types (such as String or int).
Predefined AWS event types defined in the aws-lambda-java-events library.
For example S3Event is one of the POJOs predefined in the library that provides methods for you
to easily read information from the incoming Amazon S3 event.
You can also write your own POJO class. AWS Lambda will automatically serialize and deserialize
input and output JSON based on the POJO type.
For more information, see Handler Input/Output Types (Java) (p. 66).
You can omit the Context object from the handler method signature if it isn't needed. For more
information, see The Context Object (Java) (p. 74).
For example, consider the following Java example code.
package example;
import com.amazonaws.services.lambda.runtime.Context;
public class Hello {
public String myHandler(int myCount, Context context) {
return String.valueOf(myCount);
}
}
In this example input is of type int and output is of type String. If you package this code and dependencies,
and create your Lambda function, you specify example.Hello::myHandler
(package.class::method-reference) as the handler.
In the example Java code, the first handler parameter is the input to the handler (myHandler), which can
be event data (published by an event source such as Amazon S3) or custom input you provide such as
an int (as in this example) or any custom data object.
For instructions to create a Lambda function using this Java code, see Step 2.4: (Optional) Create a
Lambda Function Authored in Java (p. 45).
65
Additional Information
The following topics provide more information about the handler.
For more information about the handler input and output types, see Handler Input/Output Types
(Java) (p. 66).
For information about using predefined interfaces to create a handler, see Leveraging Predefined
Interfaces for Creating Handler (Java) (p. 70).
If you implement these interfaces, you can validate your handler method signature at compile time.
If your Lambda function throws an exception, AWS Lambda records metrics in CloudWatch indicating
that an error occurred. For more information, see Exceptions (Java) (p. 81).
You can have similar handler functions for other simple Java types.
Note
When you invoke a Lambda function asynchronously, any return value by your Lambda function
will be ignored. Therefore you might want to set the return type to void to make this clear in your
code. For more information, see Invoke (p. 304).
To test an end-to-end example, see Step 2.4: (Optional) Create a Lambda Function Authored in
Java (p. 45).
66
package example;
import com.amazonaws.services.lambda.runtime.Context;
public class HelloPojo {
// Define two classes/POJOs for use with Lambda function.
public static class RequestClass {
...
}
public static class ResponseClass {
...
}
public static ResponseClass myHandler(RequestClass request, Context context)
{
String greetingString = String.format("Hello %s, %s.", request.getFirst
Name(), request.getLastName());
return new ResponseClass(greetingString);
}
}
AWS Lambda serializes based on standard bean naming conventions (see The Java EE 6 Tutorial). You
should use mutable POJOs with public getters and setters.
Note
You shouldn't rely on any other features of serialization frameworks such as annotations. If you
need to customize the serialization behavior, you can use the raw byte stream to use your own
serialization.
If you use POJOs for input and output, you need to provide implementation of the RequestClass and
ResponseClass types. For an example, see Example: Using POJOs for Handler Input/Output
(Java) (p. 67).
For this example, the handler receives this JSON and returns the string "Hello John Doe".
public static ResponseClass handleRequest(RequestClass request, Context context){
String greetingString = String.format("Hello %s, %s.", request.firstName,
request.lastName);
return new ResponseClass(greetingString);
}
To create a Lambda function with this handler, you must provide implementation of the input and output
types as shown in the following Java example. The HelloPojo class defines the handler method.
package example;
67
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
public class HelloPojo implements RequestHandler<RequestClass, ResponseClass>{
In order to implement the input type, add the following code to a separate file and name it
RequestClass.java. Place it next to the HelloPojo.java class in your directory structure:
package example;
public class RequestClass {
String firstName;
String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public RequestClass(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public RequestClass() {
}
}
In order to implement the output type, add the following code to a separate file and name it
ResponseClass.java. Place it next to the HelloPojo.java class in your directory structure:
package example;
public class ResponseClass {
String greetings;
68
Note
The get and set methods are required in order for the POJOs to work with AWS Lambda's built
in JSON serializer. The constructors that take no arguments are usually not required, however
in this example we provided other constructors and therefore we need to explicitly provide the
zero argument constructors.
You can upload this code as your Lambda function and test as follows:
Using the preceding code files, create a deployment package.
Upload the deployment package to AWS Lambda and create your Lambda function. You can do this
using the console or AWS CLI.
Invoke the Lambda function manually using the console or the CLI. You can use provide sample JSON
event data when you manually invoke your Lambda function. For example:
{ "firstName":"John", "lastName":"Doe" }
Follow instructions provided in the Getting Started. For more information, see Step 2.4: (Optional) Create
a Lambda Function Authored in Java (p. 45). Note the following differences:
When you create a deployment package, don't forget the aws-lambda-java-core library dependency.
When you create the Lambda function, specify example.HelloPojo::myHandler
(package.class::method) as the handler value.
Note that in this case the handler function uses parameters for both the request and response streams.
69
The following is a Lambda function example that implements the handler that uses InputStream and
OutputStream types for the input and output parameters.
Note
The input payload must be valid JSON but the output stream does not carry such a restriction.
Any bytes are supported.
package example;
import
import
import
import
java.io.InputStream;
java.io.OutputStream;
com.amazonaws.services.lambda.runtime.RequestStreamHandler;
com.amazonaws.services.lambda.runtime.Context;
Follow instructions provided in the Getting Started. For more information, see Step 2.4: (Optional) Create
a Lambda Function Authored in Java (p. 45). Note the following differences:
When you create a deployment package, don't forget the aws-lambda-java-core library dependency.
When you create the Lambda function, specify example.Hello::handler (package.class::method)
as the handler value.
70
Note
These interfaces are available in the aws-lambda-java-core library.
When you implement standard interfaces, they help you validate your method signature at compile time.
If you implement one of the interfaces, you specify package.class in your Java code as the handler
when you create the Lambda function. For example, the following is the modified create-function
CLI command from the getting started. Note that the --handler parameter specifies "example.Hello"
value:
aws lambda create-function \
--region us-west-2 \
--function-name getting-started-lambda-function-in-java \
--zip-file fileb://deployment-package (zip or jar)
path \
--role arn:aws:iam::account-id:role/lambda_basic_execution
--handler example.Hello \
--runtime java8 \
--timeout 15 \
--memory-size 512
Example 1: Creating Handler with Custom POJO Input/Output (Leverage the RequestHandler
Interface)
The example Hello class in this section implements the RequestHandler interface. The interface
defines handleRequest() method that takes in event data as input parameter of the Request type and
returns an POJO object of the Response type:
public Response handleRequest(Request request, Context context) {
...
}
The Hello class with sample implementation of the handleRequest() method is shown. For this
example, we assume event data consists of first name and last name.
package example;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.Context;
public class Hello implements RequestHandler<Request, Response> {
public Response handleRequest(Request request, Context context) {
String greetingString = String.format("Hello %s %s.", request.firstName,
request.lastName);
return new Response(greetingString);
}
}
71
"lastName" : "value2"
}
Next, you need to implement the Request and Response classes. You can use the following
implementation for testing:
The Request class:
package example;
public class Request {
String firstName;
String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Request(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public Request() {
}
}
72
You can create a Lambda function from this code and test the end-to-end experience as follows:
Using the preceding code, create a deployment package.
Upload the deployment package to AWS Lambda and create your Lambda function.
Test the Lambda function using either the console or CLI. You can specify any sample JSON data that
conform to the getter and setter in your Request class, for example:
{
"firstName":"John",
"lastName" : "Doe"
}
Follow instructions provided in the getting started (see Step 2.4: (Optional) Create a Lambda Function
Authored in Java (p. 45)). Note the following differences:
When you create a deployment package, don't forget the aws-lambda-java-core library dependency.
When you create the Lambda function specify example.Hello (package.class) as the handler
value.
73
The Hello class with sample implementation of the handleRequest() handler is shown. The handler
processes incoming event data (for example, a string "hello") by simply converting it to uppercase and
return it.
package example;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.amazonaws.services.lambda.runtime.RequestStreamHandler;
import com.amazonaws.services.lambda.runtime.Context;
public class Hello implements RequestStreamHandler {
public void handleRequest(InputStream inputStream, OutputStream outputStream,
Context context)
throws IOException {
int letter;
while((letter = inputStream.read()) != -1)
{
outputStream.write(Character.toUpperCase(letter));
}
}
}
You can create a Lambda function from this code and test the end-to-end experience as follows:
Use the preceding code to create deployment package.
Upload the deployment package to AWS Lambda and create your Lambda function.
Test the Lambda function using either the console or CLI. You can specify any sample string data, for
example:
"test"
74
75
Logging (Java)
Your Lambda function can contain logging statements. AWS Lambda writes these logs to CloudWatch.
We recommend you use one of the following to write logs.
Custom Appender for Log4j 1.2
76
AWS Lambda supports Log4j 1.2 by providing a custom appender. You can use the custom Log4j (see
Apache log4j) appender provided by Lambda for logging from your lambda functions. Every call to
Log4j methods, such as log.debug() or log.error(), will result in a CloudWatch Logs event. The
custom appender is called LambdaAppender and must be used in the log4j.properties file. You
must include the aws-lambda-java-log4j artifact (artifactId:aws-lambda-java-log4j) in
the deployment package (.jar file). For an example, see Example 1: Writing Logs Using Log4J
(Java) (p. 78).
Note
Currently, AWS Lambda supports Log4j 1.2 version.
LambdaLogger.log()
Each call to LambdaLogger.log() results in a CloudWatch Logs event, provided the event size is
within the allowed limits. For information about CloudWatch limits, see CloudWatch Limits in the Amazon
CloudWatch Developer Guide. For an example, see Example 2: Writing Logs Using LambdaLogger
(Java) (p. 79).
In addition, you can also use the following statements in your Lambda function code to generate log
entries:
System.out()
System.err()
However, note that AWS Lambda treats each line returned by System.out and System.err as a
separate event. This works well when each output line corresponds to a single log entry. When a log
entry has multiple lines of output, AWS Lambda attempts to parse them using line breaks to identify
separate events. For example, the following logs the two words ("Hello" and "world") as two separate
events:
System.out.println("Hello \n world");
77
78
Note:
AWS Lambda parses the log string in each of the System.out.println() and
System.err.println() statements logs as two separate events (note the two down arrows in the
screenshot) because of the line break.
The Log4j methods (log.debug() and log.error()) produce one CloudWatch event.
AWS Lambda runtime adds the AWSRequestId in the MDC (see Class MDC). To get this value in the
log as shown, we added %X{AWSRequestId} in the conversion pattern in the log4.properties file.
You can do the following to test the code:
Using the code, create a deployment package. In your project, don't forget to add the
log4j.properties files in the project-dir/src/main/resources/ directory.
Upload the deployment package to AWS Lambda to create your Lambda function.
To test your Lambda function use a string ("this is a test") as sample event. The handler code receives
the sample event but does nothing with it. It only shows how to write logs.
Follow the instructions provided in the Getting Started. For more information, see Step 2.4: (Optional)
Create a Lambda Function Authored in Java (p. 45). Note the following differences:
When you create a deployment package, don't forget the aws-lambda-java-log4j library dependency.
When you create the Lambda function, specify example.Hello::myHandler
(package.class::method) as the handler value.
79
Note:
AWS Lambda parses the log string in each of the System.out.println() and
System.err.println() statements logs as two separate events (note the two down arrows in the
screenshot) because of the line break.
The LambdaLogger.log() produce one CloudWatch event.
You can do the following to test the code:
Using the code, create a deployment package.
Upload the deployment package to AWS Lambda to create your Lambda function.
To test your Lambda function use a string ("this is a test") as sample event. The handler code receives
the sample event but does nothing with it. It only shows how to write logs.
Follow the instructions provided in the Getting Started. For more information, see Step 2.4: (Optional)
Create a Lambda Function Authored in Java (p. 45). Note the following differences:
When you create a deployment package, don't forget the aws-lambda-java-core library dependency.
When you create the Lambda function, specify example.Hello::myHandler
(package.class::method) as the handler value.
80
Exceptions (Java)
If your Lambda function throws an exception, AWS Lambda recognizes the failure and serializes the
exception information into JSON and returns it. Following is an example error message:
{
"errorMessage": "Name John Doe is invalid. Exception occurred...",
"errorType": "java.lang.Exception",
"stackTrace": [
"example.Hello.handler(Hello.java:9)",
"sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)",
"sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorIm
pl.java:62)",
"sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessor
Impl.java:43)",
"java.lang.reflect.Method.invoke(Method.java:497)"
]
}
Note that the stack trace is returned as the stackTrace JSON array of stack trace elements.
The method in which you get the error information back depends on the invocation type that you specified
at the time you invoked the function:
RequestResponse invocation type (that is, synchronous execution): In this case, you get the error
message back.
For example, if you invoke a Lambda function using the Lambda console, the RequestResponse is
always the invocation type and the console displays the error information returned by AWS Lambda in
the Execution result section as shown in the following image.
Event invocation type (that is, asynchronous execution): In this case AWS Lambda does not return
anything. Instead, it logs the error information in CloudWatch Logs and CloudWatch metrics.
Depending on the event source, AWS Lambda may retry the failed Lambda function. For example, if
Amazon Kinesis is the event source for the Lambda function, AWS Lambda retries the failed function
until the Lambda function succeeds or the records in the stream expire.
81
Topics
Lambda Function Handler (Python) (p. 82)
The Context Object (Python) (p. 83)
Logging (Python) (p. 85)
Exceptions (Python) (p. 88)
This example has one function called my_handler. The function returns a message containing data from
the event it received as input.
2.
Package the file and any dependencies into a .zip file. When creating the zip, include only the code
and its dependencies, not the containing folder.
For instructions, see Creating a Deployment Package (Python) (p. 98).
82
3.
Upload the .zip file using either the console or AWS CLI to create a Lambda function. You specify
the function name in the Python code to be used as the handler when you create a Lambda function.
For instructions to create a Lambda function using the console, see Step 2.1: Create a Hello World
Lambda Function (p. 39). In this example, the handler is hello_python.my_handler
(file-name.function-name). Note that the Getting Started (p. 35) uses a blueprint that provides
sample code for a Lambda function. In this case you already have a deployment package. Therefore,
in the configure function step you choose to upload a zip.
The following create-function AWS CLI command creates a Lambda function. Among other
parameters, it specifies the --handler parameter to specify the handler name.
aws lambda create-function \
--region us-west-2 \
--function-name HelloPython \
--zip-file fileb://deployment-package.zip \
--role arn:aws:iam::account-id:role/lambda_basic_execution
--handler hello_python.my_handler \
--runtime python2.7 \
--timeout 15 \
--memory-size 512
Example
Consider the following Python example. It has one function that is also the handler. The handler receives
runtime information via the context object passed as parameter.
83
The handler code in this example simply prints some of the runtime information. Each print statement
creates a log entry in CloudWatch. If you invoke the function using the Lambda console, the console
displays the logs. The from __future__ statement enables you to write code that is compatible with
Python 2 or 3.
2.
In the console, create a Lambda function using the hello-world blueprint. In runtime, choose Python
2.7. In Handler, replace lambda_function.lambda_handler with
lambda_function.get_my_log_stream. For instructions on how to do this, see Step 2.1: Create
a Hello World Lambda Function (p. 39).
Test the function, and then you can also update the code to get more context information.
The following sections provide a list of available context object methods and attributes that you can
use to get runtime information of your Lambda function.
84
Note
If AWS Lambda retries the invocation (for example, in a situation where the Lambda function
that is processing Amazon Kinesis records throws an exception), the request ID remains
the same.
log_group_name
The name of the CloudWatch log group where you can find logs written by your Lambda function.
log_stream_name
The name of the CloudWatch log stream where you can find logs written by your Lambda function.
The log stream may or may not change for each invocation of the Lambda function.
The value is null if your Lambda function is unable to create a log stream, which can happen if the
execution role that grants necessary permissions to the Lambda function does not include permissions
for the CloudWatch Logs actions.
identity
Information about the Amazon Cognito identity provider when invoked through the AWS Mobile SDK.
It can be null.
identity.cognito_identity_id
identity.cognito_identity_pool_id
client_context
Information about the client application and device when invoked through the AWS Mobile SDK. It
can be null.
client_context.client.installation_id
client_context.client.app_title
client_context.client.app_version_name
client_context.client.app_version_code
client_context.client.app_package_name
client_context.custom
A dict of custom values set by the mobile client application.
client_context.env
A dict of environment information provided by the AWS Mobile SDK.
Logging (Python)
Your Lambda function can contain logging statements. AWS Lambda writes these logs to CloudWatch.
If you use the Lambda console to invoke your Lambda function, the console displays the same logs.
The following Python statements generate log entries:
print statements.
Logger functions in the logging module (for example, logging.Logger.info and
logging.Logger.error).
Both print and logging.* functions write logs to CloudWatch Logs but the logging.* functions write
additional information to each log entry, such as time stamp and log level.
For example, consider the following Python code example.
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
85
Because the code example uses the logging module to write message to the logs, you also get some
additional information in the log such as the time stamp and the log levels. The log level identifies the
type of log, such as [INFO], [ERROR], and [DEBUG], as shown:
The screen shot shows an example Log output section in the Lambda console; you can also find these
logs in CloudWatch. For more information, see Accessing Amazon CloudWatch Logs for AWS
Lambda (p. 122).
Instead of using the logging module, you can use the print statements in your code as shown in the
following Python example:
from __future__ import print_function
def my_other_logging_handler(event, context):
print('this will also show up in cloud watch')
return 'Hello World!'
In this case only the text passed to the print method is sent to CloudWatch. The log entries will not have
additional information that the logging.* function returns. The from __future__ statement enables
you to write code that is compatible with Python 2 or 3.
86
The console uses the RequestResponse invocation type (synchronous invocation) when invoking the
function. And therefore it gets the return value ("Hello world!") back from AWS Lambda which the console
displays.
2.
3.
In the console, create a Lambda function using the hello-world-python blueprint. In runtime, choose
Python 2.7. In Handler, replace lambda_function.lambda_handler with
lambda_function.my_other_logging_handler and in Role, choose Basic execution role.
You also replace the code provided by the blueprint by the code in this section. For step-by-step
instructions to create a Lambda function using the console, see Step 2.1: Create a Hello World
Lambda Function (p. 39).
Replace the template code with the code provided in this section.
Test the Lambda function using the Sample event template called Hello World provided in the
Lambda console.
Finding Logs
You can find the logs that your Lambda function writes, as follows:
In the AWS Lambda console The Log output section in AWS Lambda console shows the logs.
In the response header, when you invoke a Lambda function programmatically If you invoke a
Lambda function programmatically, you can add the LogType parameter to retrieve the last 4 KB of
log data that is written to CloudWatch Logs. AWS Lambda returns this log information in
the x-amz-log-results header in the response. For more information, see Invoke (p. 304).
If you use AWS CLI to invoke the function, you can specify the --log-type parameter with
value Tail to retrieve the same information.
In CloudWatch Logs To find your logs in CloudWatch you need to know the log group name and
log stream name.You can use the context.logGroupName, and context.logStreamName properties
in your code to get this information. When you run your Lambda function, the resulting logs in the
console or CLI will show you the log group name and log stream name.
87
Exceptions (Python)
If your Lambda function raises an exception, AWS Lambda recognizes the failure and serializes the
exception information into JSON and returns it. Consider the following example:
def always_failed_handler(event, context):
raise Exception('I failed!')
When you invoke this Lambda function, it will raise an exception and AWS Lambda returns the following
error message:
{
"errorMessage": "I failed!",
"stackTrace": [
[
"/var/task/lambda_function.py",
3,
"my_always_fails_handler",
"raise Exception('I failed!')"
]
],
"errorType": "Exception"
}
Note that the stack trace is returned as the stackTrace JSON array of stack trace elements.
How you get the error information back depends on the invocation type that the client specifies at the
time of function invocation:
If a client specifies the RequestResponse invocation type (that is, synchronous execution), it returns
the result to the client that made the invoke call.
For example, the console always use the RequestResponse invocation type, so the console will
display the error in the Execution result section as shown:
The same information is also sent to CloudWatch and the Log output section shows the same logs.
88
If a client specifies the Event invocation type (that is, asynchronous execution), AWS Lambda will not
return anything. Instead, it logs the error information to CloudWatch Logs. You can also see the error
metrics in CloudWatch Metrics.
Depending on the event source, AWS Lambda may retry the failed Lambda function. For example, if
Amazon Kinesis is the event source, AWS Lambda will retry the failed invocation until the Lambda function
succeeds or the records in the stream expire.
2.
3.
In the console, create a Lambda function using the hello-world blueprint. In runtime, choose Python
2.7. In Handler, replace lambda_function.lambda_handler with
lambda_function.always_failed_handler. For instructions on how to do this, see Step 2.1:
Create a Hello World Lambda Function (p. 39).
Replace the template code with the code provided in this section.
Test the Lambda function using the Sample event template called Hello World provided in the
Lambda console.
89
Lambda. The console will zip up your code with the relevant configuration information into a deployment
package that the Lambda service can run.
You can also test your code in the console by manually invoking it using sample event data.
Note
The Lambda service has preinstalled the AWS SDK for Node.js.
Advanced scenario If you are writing code that uses other resources, such as a graphics library for
image processing, or you want to use the AWS CLI instead of the console, you need to first create the
Lambda function deployment package, and then use the console or the CLI to upload the package.
Note
After you create a deployment package, you may either upload it directly or upload the .zip file
first to an Amazon S3 bucket in the same AWS region where you want to create the Lambda
function, and then specify the bucket name and object key name when you create the Lambda
function using the console or the AWS CLI.
The following is an example procedure to create a deployment package (outside the console). Suppose
you want to create a deployment package that includes a filename.js code file and your code uses
the async library.
1. Open a text editor, and write your code. Save the file (for example, filename.js).
You will use the file name to specify the handler at the time of creating the Lambda function.
2. In the same directory, use npm to install the libraries that your code depends on. For example, if your
code uses the async library, use the following npm command.
npm install async
4. Zip the content of the folder, that is your deployment package (for example, sample.zip).
Then, specify the .zip file name as your deployment package at the time you create your Lambda function.
If you want to include your own binaries, including native ones, just package them in the Zip file you
upload and then reference them (including the relative path within the Zip file you created) when you call
them from Node.js or from other processes that youve previously started. Ensure that you include the
following at the start of your function code: process.env[PATH] = process.env[PATH] +
: + process.env[LAMBDA_TASK_ROOT]
For more information on including native binaries in your Lambda function package, see Running
Executables in AWS Lambda.
90
Your code will then be in the /java folder. For example, if your package name is example and you have
a Hello.java class in it, the structure will be:
project-dir/src/main/java/example/Hello.java
91
After you build the project, the resulting .jar file (that is, your deployment package), will be in the
project-dir/target subdirectory.
2.
92
Note
In the dependencies section, the groupId (that is, com.amazonaws) is the Amazon
AWS group ID for Maven artifacts in the Maven Central Repository. The artifactId
(that is, aws-lambda-java-core) is the AWS Lambda core library that provides definitions
of the RequestHandler, RequestStreamHandler, and the Context AWS Lambda
interfaces for use in your Java application. At the build time Maven resolves these
dependencies.
In the plugins section, the Apache maven-shade-plugin is a plugin that Maven will
download and use during your build process. This plugin is used for packaging jars to
create a standalone .jar (a .zip file), your deployment package.
If you are following other tutorial topics in this guide, the specific tutorials might require
you to add more dependencies. Make sure to add those dependencies as required.
3.
4.
Under the /java subdirectory you add your Java files and folder structure, if any. For example, if
you Java package name is example, and source code is Hello.java, your directory structure looks
like this:
project-dir/src/main/java/example/Hello.java
2.
93
Start Eclipse. From the Help menu in Eclipse, choose Install New Software.
In the Install window, type http://download.eclipse.org/technology/m2e/releases in
the Work with: box, and choose Add.
3.
From the File menu, choose New, and then choose Project.
b.
c.
d.
2.
Open the context (right-click) menu for the pom.xml file, choose Maven, and then choose Add
Dependency.
In the Add Dependency windows, type the following values:
Group Id: com.amazonaws
Artifact Id: aws-lambda-java-core
Version: 1.1.0
Caution
If you are following other tutorial topics in this guide, the specific tutorials might require
you to add more dependencies. Make sure to add those dependencies as required.
3.
Open the context (right-click) menu for the src/main/java subdirectory in the project, choose
New, and then choose Class.
b.
94
Package: example
Name: Hello
Caution
If you are following other tutorial topics in this guide, the specific tutorials might
recommend different package name or class name.
c.
4.
Add your Java code. If you are following other tutorial topics in this guide, add the provided code.
Note
The resulting .jar, lambda-java-example-0.0.1-SNAPSHOT.jar, is not the final
standalone .jar that you can use as your deployment package. In the next step, you add the
Apache maven-shade-plugin to create the standalone .jar. For more information, go to
Apache Maven Shade Plugin.
5.
Open the context (right-click) menu for the pom.xml file, choose Maven, and then choose Add
Plugin.
In the Add Plugin window, type the following values:
Group Id: org.apache.maven.plugins
Artifact Id: maven-shade-plugin
Version: 2.3
c.
Open the context (right-click) menu for the project, choose Run As, and then choose Maven
build ....
ii.
In the Edit Configuration windows, type package shade:shade in the Goals box.
iii.
Choose Run.
You can find the resulting standalone .jar (that is, your deployment package), in the /target
subdirectory.
Open the context (right-click) menu for the /target subdirectory, choose Show In, choose
System Explorer, and you will find the lambda-java-example-0.0.1-SNAPSHOT.jar.
95
Note
You can also build a standalone .jar (also a zipped file) as your deployment package. For
examples of creating standalone .jar using Maven, see Creating a Deployment Package
(Java) (p. 91).
The following examples use Gradle build and deployment tool to create the .zip.
Important
Gradle version 2.0 or later is required.
Example 1: Creating .zip Using Gradle and the Maven Central Repository
At the end of this walkthrough, you will have a project directory (project-dir) with content having the
following structure:
project-dir/build.gradle
project-dir/src/main/java/
The /java folder will contain your code. For example, if your package name is example, and you have
a Hello.java class in it, the structure will be:
project-dir/src/main/java/example/Hello.java
After you build the project, the resulting .zip file (that is, your deployment package), will be in the
project-dir/build/distributions subdirectory.
1.
2.
In the project-dir, create build.gradle file and add the following content:
apply plugin: 'java'
repositories {
mavenCentral()
}
dependencies {
compile (
'com.amazonaws:aws-lambda-java-core:1.1.0',
'com.amazonaws:aws-lambda-java-events:1.1.0'
)
}
96
Note
The repositories section refers to Maven Central Repository. At the build time, it fetches
the dependencies (that is, the two AWS Lambda libraries) from Maven Central.
The buildZip task describes how to create the deployment package .zip file.
For example, if you unzip the resulting .zip file you should find any of the compiled class
files and resource files at the root level. You should also find a /lib directory with the
required jars for running the code.
If you are following other tutorial topics in this guide, the specific tutorials might require
you to add more dependencies. Make sure to add those dependencies as required.
3.
4.
Under the /java subdirectory you add your Java files and folder structure, if any. For example, if
you Java package name is example, and source code is Hello.java, then your directory structure
looks like this:
project-dir/src/main/java/example/Hello.java
5.
Run the following gradle command to build and package the project in a .zip file.
project-dir> gradle build
6.
7.
Now you can upload the .zip file, your deployment package to AWS Lambda to create a Lambda
function and test it by manually invoking it using sample event data. For instruction, see Step 2.4:
(Optional) Create a Lambda Function Authored in Java (p. 45).
97
project-dir/jars/
project-dir/build.gradle
project-dir/src/main/java/
So if your Java code has example package and Hello.java class, the code will be in the following
subdirectory:
project-dir/src/main/java/example/Hello.java
Note that the dependencies specify fileTree which identifies project-dir/jars as the subdirectory
that will include all the required jars.
Now you build the package. Run the following gradle command to build and package the project in a .zip
file.
project-dir> gradle build
98
You can create a deployment package yourself or write your code directly in the Lambda console, in
which case the console creates the deployment package for you and uploads it, creating your Lambda
function. Note the following to determine if you can use the console to create your Lambda function:
Simple scenario If your custom code requires only the AWS SDK library, then you can use the inline
editor in the AWS Lambda console. Using the console, you can edit and upload your code to AWS
Lambda. The console will zip up your code with the relevant configuration information into a deployment
package that the Lambda service can run.
You can also test your code in the console by manually invoking it using sample event data.
Note
The Lambda service has preinstalled the AWS SDK for Python.
Advanced scenario If you are writing code that uses other resources, such as a graphics library for
image processing, or you want to use the AWS CLI instead of the console, you need to first create the
Lambda function deployment package, and then use the console or the CLI to upload the package.
Note
After you create a deployment package, you may either upload it directly or upload the .zip file
first to an Amazon S3 bucket in the same AWS region where you want to create the Lambda
function, and then specify the bucket name and object key name when you create the Lambda
function using the console or the AWS CLI.
The following is an example procedure to create a deployment package (outside the console).
Note
This should work for most standard installations of Python and pip when using pure Python
modules in your Lambda function. If you are including modules that have native dependencies
or have Python installed with Homebrew on OS X, you should see the next section which provides
instructions to create a deployment package when using Virtualenv. For more information, see
Create Deployment Package Using a Python Environment Created with Virtualenv (p. 100) and
the Virtualenv website.
You will use pip to install dependencies/libraries. For information to install pip, go to Installation.
1.
2.
3.
Save all of your Python source files (the .py files) at the root level of this directory.
Install any libraries using pip. Again, you install these libraries at the root level of the directory.
pip install module-name -t /path/to/project-dir
For example, the following command installs the requests HTTP library in the project-dir
directory.
pip install requests -t /path/to/project-dir
If using Mac OS X and you have Python installed using Homebrew (see Homebrew), the preceding
command will not work. A simple workaround is to add a setup.cfg file in your
/path/to/project-dir with the following content.
[install]
prefix=
4.
Zip the content of the project-dir directory, which is your deployment package.
99
Important
Zip the directory content, not the directory. The contents of the Zip file are available as the
current working directory of the Lambda function. For example:
/project-dir/codefile.py/lib/yourlibraries
Note
AWS Lambda includes the AWS SDK for Python (Boto 3), so you don't need to include it in your
deployment package. However, if you want to use a version of Boto3 other than the one included
by default, you can include it in your deployment package.
path/to/my/virtual-env/bin/activate
Also, suppose you have installed the requests package in the activated environment (assume that
you will you use these in your code). You can install these packages as follows :
pip install requests
First, create .zip file with your Python code you want to upload to AWS Lambda.
Add the libraries from preceding activated virtual environment to the .zip file. That is, you add the
content of the following directory to the .zip file (note again that you add the content of the directory
and not the directory itself).
For Windows the directory is:
%VIRTUAL_ENV%\Lib\site-packages
100
$VIRTUAL_ENV/lib/python2.7/site-packages
Note
If you don't find the packages in the site-packages directory in your virtual environment,
you might find it in the dist-packages directory.
For an example of creating a Python deployment package, see Python (p. 136).
101
Aliases enable you to abstract the process of promoting new Lambda function versions into production
from the mapping of the Lambda function version and its event source. For more information, see How
It Works (p. 3).
For example, suppose Amazon S3 is the event source that invokes your Lambda function when new
objects are created in a bucket. When Amazon S3 is your event source, you store the event source
mapping information in the bucket notification configuration. In the configuration you can identify the
Lambda function ARN that Amazon S3 can invoke, but, in this case, each time you publish a new version
of your Lambda function you need to update the notification configuration so that Amazon S3 invokes
the correct version. Instead of specifying the function ARN, you can specify an alias ARN in the notification
configuration (for example, PROD alias ARN). As you promote new versions of your Lambda function
into production, you only need to update the PROD alias to point to the latest stable version, and you
don't need to update the notification configuration in Amazon S3.
The same applies when you need to roll back to a previous version of your Lambda function. In this
scenario, you just update the PROD alias to point to a different function version, and there is no need to
update event source mappings.
We recommend you use versioning and aliases to deploy your Lambda functions when building applications
with multiple dependencies and developers involved.
For detailed information, see the following topics:
Topics
Versioning (p. 102)
Aliases (p. 106)
Versioning, Aliases, and Resource Policies (p. 114)
Managing Versioning (p. 116)
You can refer to this function using its Amazon Resource Name (ARN). There are two ARNs associated
with this initial version:
102
Note
Unless you choose to publish versions, the $LATEST version is the only Lambda function version
you have. You can use either the qualified or unqualified ARN in your event source mapping to
invoke this $LATEST version.
The following is an example response of a CreateFunction API call:
{
"CodeSize": 287,
"Description": "test function."
"FunctionArn": "arn:aws:lambda:aws-region:acct-id:function:helloworld",
"FunctionName": "helloworld",
"Handler": "helloworld.handler",
"LastModified": "2015-07-16T00:34:31.322+0000",
"MemorySize": 128,
"Role": "arn:aws:iam::acct-id:role/lambda_basic_execution",
"Runtime": "nodejs4.3",
"Timeout": 3,
"CodeSHA256": "OjRFuuHKizEE8tHFIMsI+iHR6BPAfJ5S0rW31Mh6jKg=",
"Version": "$LATEST"
}
103
Note
Lambda will only publish a new version if the code has not yet been published or if the code has
changed when compared against the $LATEST version. If there is no change, the $LATEST
published version will be returned.
We recommend that you publish a version at the same time that you create your Lambda function or
update your Lambda function code, especially when multiple developers contribute to the same Lambda
104
function development. You can use the publish parameter in your request to do this. When you have
multiple developers working on a project, it is possible for developer A to create a Lambda function
($LATEST version) and before developer A publishes a version, developer B updates the code (deployment
package) associated with the $LATEST version. In this case, you lose the original code that developer A
uploaded. When both developers add the publish parameter it prevents the race condition described.
Note
The published versions are immutable. That is, you cannot change code or configuration
information associated with a version.
Each version of a Lambda function is a unique resource with a Amazon Resource Name (ARN). The
following example shows the ARN of version number 1 of the helloworld Lambda function:
arn:aws:lambda:aws-region:acct-id:function:helloworld:1
Note
This is a qualified ARN, where the version number is a suffix. Published versions can have only
qualified ARN.
You can publish multiple versions. Each time you publish a version, AWS Lambda copies $LATEST
version (code and configuration information) to create a new version. When you publish additional versions,
AWS Lambda assigns a monotonically increasing sequence number for versioning, even if the function
was deleted and re-created. Version numbers are never reused, even for a function that has been deleted
and re-created, so that the consumer of that version can depend on the executable of that version to
never change (except if it's deleted). If you want to re-use a qualifier, use aliases with your versions.
Aliases can be deleted and re-created with the same name.
105
You can update code and configuration information (such as description, memory size, and execution
timeout) of the $LATEST version of the Lambda function. However, published versions are immutable.
That is, you cannot change code or configuration information.
Important
You can delete a specific function version, but you cannot delete the $LATEST.
Related Topics
Introduction to AWS Lambda Aliases (p. 106)
Managing Versioning Using the AWS Management Console, the AWS CLI, or Lambda APIs (p. 116)
Note
In this context, the terms promotion and roll back refer to the remapping of aliases to different
function versions.
Simplify management of event source mappings Instead of using Lambda function ARNs in event
source mappings, by using an alias ARN you ensure that you don't need to update your event source
mappings when you promote a new version or roll back to a previous version.
An AWS Lambda alias is a resource similar to a Lambda function. However, you can't create an alias
independently. You create an alias for an existing Lambda function. If a Lambda function is a resource,
you can think of an AWS Lambda alias as a subresource that is associated with a Lambda function.
106
Both the Lambda function and alias are AWS Lambda resources, and like all other AWS resources they
both have unique Amazon Resource Names (ARNs). The following example shows a Lambda function
(the $LATEST version), with one published version. Each version has an alias pointing to it.
You can access the function using either the function ARN or the alias ARN.
Because the function version is $LATEST, you can access it using the qualified or unqualified function
ARN.
Qualified function ARN (with the $LATEST version suffix):
arn:aws:lambda:aws-region:acct-id:function:helloworld:$LATEST
When using any of the alias ARNs, you are using a qualified ARN. Each alias ARN has an alias name
suffix.
arn:aws:lambda:aws-region:acct-id:function:helloworld:PROD
arn:aws:lambda:aws-region:acct-id:function:helloworld:BETA
arn:aws:lambda:aws-region:acct-id:function:helloworld:DEV
AWS Lambda provides the following APIs for you to create and manages aliases:
CreateAlias (p. 276)
UpdateAlias (p. 324)
GetAlias (p. 293)
ListAliases (p. 310)
DeleteAlias (p. 288)
107
Test the function version using event sources in a beta environment, in a stable way while
continuing to develop newer versions.
You publish a version from the $LATEST and have another alias (BETA) point to it. This allows you
to associate your beta event sources to this specific alias. In the event source mappings, use the
BETA alias to associate your Lambda function with the event source.
108
Promote the Lambda function version in production to work with event sources in production
environment.
After testing the BETA version you can define the production version by creating an alias that maps
to version 1. This means you want to point your production event sources to this specific version.
You do this by creating a PROD alias and using the PROD alias ARN in all of your production event
source mappings.
109
If you want to try creating this setup using AWS CLI, see Tutorial: Using AWS Lambda Aliases (p. 110).
Related Topics
Introduction to AWS Lambda Versioning (p. 102)
Tutorial: Using AWS Lambda Aliases (p. 110)
Managing Versioning Using the AWS Management Console, the AWS CLI, or Lambda APIs (p. 116)
First, you need to create a deployment package that you can upload to create your Lambda function.
a.
110
2.
b.
c.
Create an IAM role (execution role) that you can specify at the time you create your Lambda function.
a.
b.
c.
3.
Write down the Amazon Resource Name (ARN) of the IAM role. You need this value when you
create your Lambda function in the next step.
The response returns the configuration information showing $LATEST as the function version as
shown in the following example response:
{
"CodeSha256": "OjRFuuHKizEE8tHFIMsI+iHR6BPAfJ5S0rW31Mh6jKg=",
"FunctionName": "helloworld",
"CodeSize": 287,
"MemorySize": 128,
"FunctionArn": "arn:aws:lambda:us-west-2:account-id:function:helloworld",
"Version": "$LATEST",
"Role": "arn:aws:iam::account-id:role/lambda_basic_execution",
"Timeout": 3,
"LastModified": "2015-09-30T18:39:53.873+0000",
"Handler": "helloworld.handler",
"Runtime": "nodejs4.3",
"Description": ""
}
111
4.
Create an alias (DEV) that points to the $LATEST version of the helloworld Lambda function:
aws lambda create-alias \
--region us-west-2 \
--function-name helloworld \
--description "sample alias" \
--function-version "\$LATEST" \
--name DEV \
--profile adminuser
The response returns the alias information, including the function version it is pointing to and the
alias ARN. The ARN is the same as the function ARN with an alias name suffix. The following is an
example response:
{
"AliasArn": "arn:aws:lambda:us-west-2:account-id:function:helloworld:DEV",
"FunctionVersion": "$LATEST",
"Name": "DEV",
"Description": "sample alias"
}
5.
The response returns configuration information of the function version, including the version number,
and the function ARN with the version suffix. The following is an example response:
{
"CodeSha256": "OjRFuuHKizEE8tHFIMsI+iHR6BPAfJ5S0rW31Mh6jKg=",
"FunctionName": "helloworld",
"CodeSize": 287,
"MemorySize": 128,
"FunctionArn": "arn:aws:lambda:us-west-2:account-id:function:hello
world:1",
"Version": "1",
"Role": "arn:aws:iam::account-id:role/lambda_basic_execution",
"Timeout": 3,
"LastModified": "2015-10-03T00:48:00.435+0000",
"Handler": "helloworld.handler",
"Runtime": "nodejs4.3",
"Description": ""
}
6.
Create an alias (BETA) for the for the helloworld Lambda function version 1.
aws lambda create-alias \
--region us-west-2 \
--function-name helloworld \
112
Now you have two aliases for the helloworld function. The DEV alias points to the $LATEST function
version, and the BETA alias points to version 1 of the Lambda function.
7.
Now suppose you want to put the version 1 of the helloworld function in production. Create another
alias (PROD) that points to version 1.
aws lambda create-alias \
--region us-west-2 \
--function-name helloworld \
--description "sample alias" \
--function-version 1 \
--name PROD \
--profile adminuser
At this time you have both the BETA and PROD aliases pointing to version 1 of the Lambda function.
8.
You can now publish a newer version (for example, version 2), but first you need to update your code
and upload a modified deployment package. If the $LATEST version is not changed, you cannot
publish more than one version of it. Assuming you updated the deployment package, uploaded it,
and published version 2, you can now change the BETA alias to point to version 2 of the Lambda
function.
aws lambda update-alias \
--region us-west-2 \
--function-name helloworld \
--function-version 2 \
--name BETA \
--profile adminuser
Now you have three aliases pointing to a different version of the Lambda function (DEV alias points
to the $LATEST version, BETA alias points to version 2, and the PROD alias points to version 1 of the
Lambda function.
For information about using the AWS Lambda console to manage versioning, see Managing Versioning
Using the AWS Management Console, the AWS CLI, or Lambda APIs (p. 116).
113
In the push model, you grant event sources permissions using a resource policy that you attach to your
Lambda function. In versioning, the permissions you add are specific to the qualifier that you specify
in the AddPermission request (see Versioning, Aliases, and Resource Policies (p. 114)).
For example, the following AWS CLI command grants Amazon S3 permissions to invoke the PROD
alias of the helloworld Lambda function (note that the --qualifier parameter specifies the alias
name).
aws lambda add-permission \
--region us-west-2 \
--function-name helloworld \
--qualifier PROD \
--statement-id 1 \
--principal s3.amazonaws.com \
--action lambda:InvokeFunction \
--source-arn arn:aws:s3:::examplebucket \
--source-account 111111111111 \
--profile adminuser
In this case, Amazon S3 is now able to invoke the PROD alias and AWS Lambda can then execute
the helloworld Lambda function version that the PROD alias points to. For this to work, you must use
the PROD alias ARN in the S3 bucket's notification configuration.
For information about how to handle Amazon S3 events, see Tutorial: Using AWS Lambda with Amazon
S3 (p. 127).
Note
If you use the AWS Lambda console to add an event source for your Lambda function, the
console adds the necessary permissions for you.
114
You can invoke for example the helloworld function version 1 using any of the following two ARNs:
Using the qualified function ARN:
arn:aws:lambda:aws-region:acct-id:function:helloworld:1
Note
An unqualified function ARN (function ARN without a version or alias suffix), maps to the
$LATEST version.
Using the BETA alias ARN:
arn:aws:lambda:aws-region:acct-id:function:helloworld:BETA
In a push model, event sources (such as Amazon S3 and custom applications) can invoke any of the
Lambda function versions as long you grant the necessary permissions to these event sources by using
an access policy associated with the Lambda function. For more information about the push model, see
Event Source Mapping (p. 10).
Assuming that you grant permission, the next question is, "can an event source invoke a function version
using any of the associated ARNs?" The answer is, it depends on how you identified function in your add
permissions request (see AddPermission (p. 273)). The key to understanding this is that the permission
you grant apply only to the ARN used in the add permission request:
If you use a qualified function name (such as helloworld:1), the permission is valid for invoking the
helloworld function version 1 only using its qualified ARN (using any other ARNs will result in a
permission error).
115
If you use an alias name (such as helloworld:BETA), the permission is valid only for invoking the
helloworld function using the BETA alias ARN (using any other ARNs will result in a permission
error, including the function version ARN to which the alias points).
If you use an unqualified function name (such as helloworld), the permission is valid only for invoking
the helloworld function using the unqualified function ARN (using any other ARNs will result in a
permission error).
Note
Note that even though the access policy is only on the unqualified ARN, the code and
configuration of the invoked Lambda function is still from function version $LATEST. The
unqualified function ARN maps to the $LATEST version but the permissions you add are
ARN-specific.
If you use a qualified function name using the $LATEST version (helloworld:$LATEST), the permission
is valid for invoking the helloworld function version $LATEST only using its qualified ARN (using
unqualified ARN will result in a permission error).
116
The expanded Qualifiers menu displays a Versions and Aliases tab, as shown in the following screen
shot. In the Versions pane, you can see a list of versions for the selected function. If you have not
previously published a version for the selected function, the Versions pane lists only the $LATEST version,
as shown:
Choose the Aliases tab to see a list of aliases for the function. Initially, you won't have any aliases, as
shown following:
117
Now, you can publish a version or create aliases for the selected Lambda function using the Actions
menu.
To learn about versioning and aliases, see AWS Lambda Function Versioning and Aliases (p. 101).
118
associated CloudWatch metrics. You can leverage these metrics to set CloudWatch custom alarms. For
more information about CloudWatch, see the Amazon CloudWatch Developer Guide.
You can view request rates and error rates for each of your Lambda functions by using the AWS Lambda
console, the CloudWatch console, and other Amazon Web Services (AWS) resources. The following
topics describe Lambda CloudWatch metrics and how to access them.
Accessing Amazon CloudWatch Metrics for AWS Lambda (p. 120)
AWS Lambda Metrics (p. 123)
You can insert logging statements into your code to help you validate that your code is working as expected.
Lambda automatically integrates with Amazon CloudWatch Logs and pushes all logs from your code to
a CloudWatch Logs group associated with a Lambda function (/aws/lambda/<function name>). To learn
more about log groups and accessing them through the CloudWatch console, see the Monitoring System,
Application, and Custom Log Files in the Amazon CloudWatch Developer Guide. For information about
how to access CloudWatch log entries, see Accessing Amazon CloudWatch Logs for AWS Lambda (p. 122).
Note
If your Lambda function code is executing, but you don't see any log data being generated after
several minutes, this could mean your execution role for the Lambda function did not grant
permissions to write log data to CloudWatch Logs. For information about how to make sure that
you have set up the execution role correctly to grant these permissions, see Manage Permissions:
Using an IAM Role (Execution Role) (p. 31).
Check your code and verify that it is working correctly. An increased error rate would indicate that it
is not.
You can test your code locally as you would any other Node.js function, or you can test it within the
Lambda console using the console's test invoke functionality, or you can use the AWS CLI Invoke
command. Each time the code is executed in response to an event, it writes a log entry into the log
group associated with a Lambda function, which is /aws/lambda/<function name>.
Following are some examples of errors that might show up in the logs:
If you see a stack trace in your log, there is probably an error in your code. Review your code and
debug the error that the stack trace refers to.
If you see a permissions denied error in the log, the IAM role you have provided as an execution
role may not have the necessary permissions. Check the IAM role and verify that it has all of the
necessary permissions to access any AWS resources that your code references. To ensure that
you have correctly set up the execution role, see Manage Permissions: Using an IAM Role
(Execution Role) (p. 31).
119
If you see a timeout exceeded error in the log, your timeout setting exceeds the run time of
your function code. This may be because the timeout is too low, or the code is taking too long to
execute.
If you see a memory exceeded error in the log, your memory setting is too low. Set it to a higher
value. For information about memory size limits, see CreateFunction (p. 283). When you change
the memory setting, it can also change how you are charged for duration. For information about
pricing, see the AWS Lambda product website.
2.
2.
If your code is taking too long to execute, it could be that it does not have enough compute resources
to execute its logic. Try increasing the memory allocated to your function and testing the code again,
using the Lambda console's test invoke functionality. You can see the memory used, code execution
time, and memory allocated in the function log entries. Changing the memory setting can change
how you are charged for duration. For information about pricing, see AWS Lambda.
Investigate the source of the execution bottleneck that is using logs.
You can test your code locally, as you would with any other Node.js function, or you can test it within
Lambda using the test invoke capability on the Lambda console, or using the asyncInvoke command
by using AWS CLI. Each time the code is executed in response to an event, it writes a log entry into
the log group associated with a Lambda function, which is named aws/lambda/<function name>.
Add logging statements around various parts of your code, such as callouts to other services, to see
how much time it takes to execute different parts of your code.
120
You can monitor metrics for Lambda and view logs by using the Lambda console, the CloudWatch console,
the AWS CLI, or the CloudWatch API. The following procedures show you how to access metrics using
these different methods.
Sign in to the AWS Management Console and open the AWS Lambda console at https://
console.aws.amazon.com/lambda/.
If you have not created a Lambda function before, see Getting Started (p. 35).
3.
On the Functions page, choose the function name and then choose the Monitoring tab.
4.
A graphical representation of the metrics for the Lambda function are shown.
Choose View logs in CloudWatch to view the logs.
121
Note
There is no additional charge for using Lambda logs; however, standard CloudWatch Logs
charges apply. For more information, see CloudWatch Pricing.
Sign in to the AWS Management Console and open the AWS Lambda console at https://
console.aws.amazon.com/lambda/.
If you have not created a Lambda function before, see Getting Started (p. 35).
On the Functions page, choose the function name and then choose the Monitoring tab.
4.
A graphical representation of the metrics for the Lambda function are shown.
Choose View logs in CloudWatch to view the logs.
For more information on accessing CloudWatch Logs, see the following guides:
Amazon CloudWatch Developer Guide
Amazon CloudWatch Logs API Reference
Monitoring Log Files in the Amazon CloudWatch Developer Guide
122
Description
Invocations
Errors
Measures the number of invocations that failed due to errors in the function
(response code 4XX). This replaces the deprecated ErrorCount metric. Failed
invocations may trigger a retry attempt that succeeds. This includes:
Permissions errors
This does not include invocations that fail due to invocation rates exceeding
default concurrent limits (error code 429) or failures due to internal service
errors (error code 500).
Units: Count
Duration
Measures the elapsed wall clock time from when the function code starts
executing as a result of an invocation to when it stops executing. This replaces
the deprecated Latency metric. The maximum data point value possible is
the function timeout configuration. The billed duration will be rounded up to
the nearest 100 millisecond. Note that AWS Lambda only sends these metrics
to CloudWatch if they have a nonzero value.
Units: Milliseconds
123
Metric
Description
Throttles
Errors/Invocations Ratio
When calculating the error rate on Lambda function invocations, its important to distinguish
between an invocation request and an actual invocation. It is possible for the error rate to exceed
the number of billed Lambda function invocations. Lambda reports an invocation metric only if
the Lambda function code is executed. If the invocation request yields a throttling or other
initialization error that prevents the Lambda function code from being invoked, Lambda will report
an error, but it does not log an invocation metric.
Lambda emits Invocations=1 when the function is executed. If the Lambda function is not
executed, nothing is emitted.
Lambda emits a data point for Errors for each invoke request. Errors=0 means that there
is no function execution error. Errors=1 means that there is a function execution error.
Lambda emits a data point for Throttles for each invoke request. Throttles=0 means
there is no invocation throttle. Throttles=1 means there is an invocation throttle.
Description
FunctionName
Resource
Version
Alias
124
125
configuration that identifies the type of event that you want Amazon S3 to publish and the Lambda function
that you want to invoke.
Note the following about how the Amazon S3 and AWS Lambda integration works:
Non-stream based (async) model This is a model (see Event Source Mapping (p. 10)), where
Amazon S3 monitors a bucket and invokes the Lambda function by passing the event data as a
parameter. In a push model, you maintain event source mapping within Amazon S3 using the bucket
notification configuration. In the configuration, you specify the event types that you want Amazon S3
to monitor and which AWS Lambda function you want Amazon S3 to invoke. For more information,
see Configuring Amazon S3 Event Notifications in the Amazon Simple Storage Service Developer
Guide.
Asynchronous invocation AWS Lambda invokes a Lambda function using the Event invocation
type (asynchronous invocation). For more information about invocation types, see Invocation
Types (p. 9).
Event structure The event your Lambda function receives is for a single object and it provides
information, such as the bucket name and object key name.
Note that there are two types of permissions policies that you work with when you set up the end-to-end
experience:
Permissions for your Lambda function Regardless of what invokes a Lambda function, AWS
Lambda executes the function by assuming the IAM role (execution role) that you specify at the time
you create the Lambda function. Using the permissions policy associated with this role, you grant your
Lambda function the permissions that it needs. For example, if your Lambda function needs to read
an object, you grant permissions for the relevant Amazon S3 actions in the permissions policy. For
more information, see Manage Permissions: Using an IAM Role (Execution Role) (p. 31).
Permissions for Amazon S3 to invoke your Lambda function Amazon S3 cannot invoke your
Lambda function without your permission.You grant this permission via the permissions policy associated
with the Lambda function.
The following diagram summarizes the flow:
126
Important
You must use two buckets. If you use the same bucket as the source and the target, each
thumbnail uploaded to the source bucket triggers another object-created event, which then
invokes the Lambda function again, creating an unwanted recursion.
Implementation Summary
The following diagram illustrates the application flow:
127
In Lambda:
A Lambda function.
An access permissions policy associated with your Lambda function You grant Amazon S3 permissions
to invoke the Lambda function using this permissions policy. You will also restrict the permissions so
that Amazon S3 can invoke the Lambda function only for object-created events from a specific bucket
that is owned by a specific AWS account.
Note
It is possible for an AWS account to delete a bucket and some other AWS account to later
create a bucket with the same name. The additional conditions ensure that Amazon S3 can
invoke the Lambda function only if Amazon S3 detects object-created events from a specific
bucket owned by a specific AWS account.
For more information, see How It Works (p. 3).
In IAM:
Administrator user Called adminuser. Using root credentials of an AWS account is not recommended.
Instead, use the adminuser credentials to perform the steps in this tutorial.
An IAM role (execution role) You grant permissions that your Lambda function needs through the
permissions policy associated with this role.
In Amazon S3:
Two buckets named source and sourceresized. Note that source is a placeholder name and you
need to replace it with your actual bucket name. For example, if you have a bucket named example
as your source, you will create exampleresized as the target bucket.
Notification configuration on the source bucket You add notification configuration on your source
bucket identifying the type of events (object-created events) you want Amazon S3 to publish to AWS
Lambda and the Lambda function to invoke. For more information about the Amazon S3 notification
feature, see Setting Up Notification of Bucket Events in Amazon Simple Storage Service Developer
Guide..
128
Now you are ready to start the tutorial. Note that after the initial preparation, the tutorial is divided into
two main sections:
First, you complete the necessary setup steps to create a Lambda function and invoke it manually
using Amazon S3 sample event data. This intermediate testing verifies that the function works.
Second, you add notification configuration to your source bucket so that Amazon S3 can invoke your
Lambda function when it detects object-created events.
Next Step
Step 1: Prepare (p. 129)
Step 1: Prepare
In this section, you do the following:
Sign up for an AWS account and set up the AWS CLI.
Create two buckets (source and sourceresized bucket) with a sample .jpg object (HappyFace.jpg)
in the source bucket. For instructions, see the following procedure.
Step 1.1: Sign Up for AWS and Set Up the AWS CLI
Make sure you have completed the following steps:
Signed up for an AWS account and created an administrator user in the account (called adminuser).
Installed and set up the AWS CLI.
For instructions, see Step 1: Set Up an AWS Account and the AWS CLI (p. 35).
Important
Both the source bucket and your Lambda function must be in the same AWS region. In addition,
the example code used for the Lambda function also assumes that both of the buckets are in
the same region. In this tutorial, we use the us-west-2 region.
1. Using the IAM User Sign-In URL, sign in to the Amazon S3 console as adminuser.
2. 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
mybucketresized.
For instructions, see Create a Bucket in the Amazon Simple Storage Service Getting Started Guide.
3. 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.
Next Step
Step 2: Create a Lambda Function and Invoke It Manually (Using Sample Event Data) (p. 130)
129
Note
To see more examples of using other AWS services within your function, including calling
other Lambda functions, see AWS SDK for JavaScript
Create an IAM role (execution role). At the time you upload the deployment package, you need to
specify an IAM role (execution role) that Lambda can assume to execute the function on your behalf.
Create the Lambda function by uploading the deployment package, and then test it by invoking it
manually using sample Amazon S3 event data.
Topics
Step 2.1: Create a Deployment Package (p. 130)
Step 2.2: Create the Execution Role (IAM Role) (p. 137)
Step 2.3: Create the Lambda Function and Test It Manually (p. 138)
Node.js
The deployment package is a .zip file containing your Lambda function code and dependencies.
1.
2.
3.
Install the Node.js platform. For more information, see the Node.js website.
Install dependencies. The code examples use the following libraries:
AWS SDK for JavaScript in Node.js
gm, GraphicsMagick for node.js
Async utility module
The AWS Lambda runtime already has the AWS SDK for JavaScript in Node.js, so you only need
to install the other libraries. Open a command prompt, navigate to the examplefolder, and install
the libraries using the npm command, which is part of Node.js.
npm install async gm
4.
130
131
);
var width = scalingFactor * size.width;
var height = scalingFactor * size.height;
// Transform the image buffer in memory.
this.resize(width, height)
.toBuffer(imageType, function(err, buffer) {
if (err) {
next(err);
} else {
next(null, response.ContentType, buffer);
}
});
});
},
function upload(contentType, data, next) {
// Stream the transformed image to a different S3 bucket.
s3.putObject({
Bucket: dstBucket,
Key: dstKey,
Body: data,
ContentType: contentType
},
next);
}
], function (err) {
if (err) {
console.error(
'Unable to resize ' + srcBucket + '/' + srcKey +
' and upload to ' + dstBucket + '/' + dstKey +
' due to an error: ' + err
);
} else {
console.log(
'Successfully resized ' + srcBucket + '/' + srcKey +
' and uploaded to ' + dstBucket + '/' + dstKey
);
}
callback(null, "message");
}
);
};
Note
The code sample is compliant with the Node.js runtime v4.3. For more information, see
Programming Model (Node.js) (p. 51)
5.
132
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.
6.
Save the file as CreateThumbnail.js in examplefolder. After you complete this step, you will
have the following folder structure:
CreateThumbnail.js
/node_modules/gm
/node_modules/async
7.
Next Step
Step 2.2: Create the Execution Role (IAM Role) (p. 137)
Java
The following is example Java code that reads incoming Amazon S3 events and creates a thumbnail.
Note that it implements the RequestHandler interface provided in the aws-lambda-java-core library.
Therefore, at the time you create a Lambda function you specify the class as the handler (that is,
example.S3EventProcessorCreateThumbnail). For more information about using interfaces to
provide a handler, see Leveraging Predefined Interfaces for Creating Handler (Java) (p. 70).
The S3Event type that the handler uses as the input type is one of the predefined classes in the
aws-lambda-java-events library that provides methods for you to easily read information from the
incoming Amazon S3 event. The handler returns a string as output.
package example;
import
import
import
import
import
import
import
import
import
import
import
java.awt.Color;
java.awt.Graphics2D;
java.awt.RenderingHints;
java.awt.image.BufferedImage;
java.io.ByteArrayInputStream;
java.io.ByteArrayOutputStream;
java.io.IOException;
java.io.InputStream;
java.net.URLDecoder;
java.util.regex.Matcher;
java.util.regex.Pattern;
import javax.imageio.ImageIO;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.S3Event;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.event.S3EventNotification.S3EventNotification
Record;
133
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.S3Object;
public class S3EventProcessorCreateThumbnail implements
RequestHandler<S3Event, String> {
private static final float MAX_WIDTH = 100;
private static final float MAX_HEIGHT = 100;
private final String JPG_TYPE = (String) "jpg";
private final String JPG_MIME = (String) "image/jpeg";
private final String PNG_TYPE = (String) "png";
private final String PNG_MIME = (String) "image/png";
public String handleRequest(S3Event s3event, Context context) {
try {
S3EventNotificationRecord record = s3event.getRecords().get(0);
String srcBucket = record.getS3().getBucket().getName();
// Object key may have spaces or unicode non-ASCII characters.
String srcKey = record.getS3().getObject().getKey()
.replace('+', ' ');
srcKey = URLDecoder.decode(srcKey, "UTF-8");
String dstBucket = srcBucket + "resized";
String dstKey = "resized-" + srcKey;
// Sanity check: validate that source and destination are different
// buckets.
if (srcBucket.equals(dstBucket)) {
System.out
.println("Destination bucket must not match source
bucket.");
return "";
}
// Infer the image type.
Matcher matcher = Pattern.compile(".*\\.([^\\.]*)").matcher(srcKey);
if (!matcher.matches()) {
System.out.println("Unable to infer image type for key "
+ srcKey);
return "";
}
String imageType = matcher.group(1);
if (!(JPG_TYPE.equals(imageType)) && !(PNG_TYPE.equals(imageType)))
{
System.out.println("Skipping non-image " + srcKey);
return "";
}
// Download the image from S3 into a stream
AmazonS3 s3Client = new AmazonS3Client();
S3Object s3Object = s3Client.getObject(new GetObjectRequest(
srcBucket, srcKey));
InputStream objectData = s3Object.getObjectContent();
// Read the source image
134
Amazon S3 invokes your Lambda function using the Event invocation type, where AWS Lambda executes
the code asynchronously. What you return does not matter. However, in this case we are implementing
an interface that requires us to specify a return type, so in this example the handler uses String as the
return type.
135
Using the preceding code (in a file named ProcessKinesisEvents.java), create a deployment
package. Make sure that you add the following dependencies:
aws-lambda-java-core.
aws-lambda-java-events
These can be found at aws-lambda-java-libs.
For more information, see Programming Model for Authoring Lambda Functions in Java (p. 63).
Your deployment package can be a .zip file or a standalone .jar. You can use any build and packaging
tool you are familiar with to create a deployment package. For examples of how to use the Maven build
tool to create a standalone .jar, see Creating a .jar Deployment Package Using Maven without any IDE
(Java) (p. 91) and Creating a .jar Deployment Package Using Maven and Eclipse IDE (Java) (p. 93). For
an example of how to use the Gradle build tool to create a .zip file, see Creating a .zip Deployment
Package (Java) (p. 96).
After you verify that your deployment package is created, go to the next step to create an IAM role
(execution role). You specify this role at the time you create your Lambda function.
Next Step
Step 2.2: Create the Execution Role (IAM Role) (p. 137)
Python
In this section, you create an example Python function and install dependencies.
1.
Open a text editor, and copy the following code. The code uploads the resized image to a different
bucket with the same image name, as shown following:
source-bucket/image.png -> source-bucketresized/image.png
from __future__ import print_function
import boto3
import os
import sys
import uuid
from PIL import Image
import PIL.Image
s3_client = boto3.client('s3')
def resize_image(image_path, resized_path):
with Image.open(image_path) as image:
image.thumbnail(tuple(x / 2 for x in image.size))
image.save(resized_path)
def handler(event, context):
for record in event['Records']:
bucket = record['s3']['bucket']['name']
key = record['s3']['object']['key']
download_path = '/tmp/{}{}'.format(uuid.uuid4(), key)
upload_path = '/tmp/resized-{}'.format(key)
s3_client.download_file(bucket, key, download_path)
resize_image(download_path, upload_path)
s3_client.upload_file(upload_path, '{}resized'.format(bucket), key)
136
2.
3.
4.
5.
6.
7.
8.
Note
AWS Lambda includes the AWS SDK for Python (Boto 3), so you don't need to include it
in your deployment package, but you can optionally include it for local testing.
9.
10. Add the contents of lib and lib64 site-packages to your .zip file.
cd $VIRTUAL_ENV/lib/python2.7/site-packages
zip -r9 ~/CreateThumbnail.zip *
cd $VIRTUAL_ENV/lib64/python2.7/site-packages
zip -r9 ~/CreateThumbnail.zip *
Next Step
Step 2.2: Create the Execution Role (IAM Role) (p. 137)
137
2.
Follow the steps in Creating a Role to Delegate Permissions to an AWS Service in the IAM User
Guide to create an IAM role (execution role). As you follow the steps to create a role, note the
following:
In Role Name, use a name that is unique within your AWS account (for example,
lambda-s3-execution-role).
In Select Role Type, choose AWS Service Roles, and then choose AWS Lambda. This grants
the AWS Lambda service permissions to assume the role.
In Attach Policy, choose AWSLambdaExecute.
3.
Write down the role ARN. You will need it in the next step when you create your Lambda function.
Next Step
Step 2.3: Create the Lambda Function and Test It Manually (p. 138)
Step 2.3.1: Create the Lambda Function (Upload the Deployment Package)
In this step, you upload the deployment package using the AWS CLI.
1.
At the command prompt, run the following Lambda AWS CLI create-function command using
the adminuser as the --profile. You need to update the command by providing the .zip file path
and the execution role ARN. For the runtime parameter, choose between nodejs4.3, python2.7
or java8, depending on the code sample you when you created your deployment package.
$ aws lambda create-function \
--region us-west-2 \
--function-name CreateThumbnail \
--zip-file fileb://file-path/CreateThumbnail.zip \
--role role-arn \
--handler CreateThumbnail.handler \
--runtime runtime \
--profile adminuser \
--timeout 10 \
--memory-size 1024
138
Optionally, you can upload the .zip file to an Amazon S3 bucket in the same AWS region, and then
specify the bucket and object name in the preceding command.You need to replace the --zip-file
parameter by the --code parameter, as shown following:
--code S3Bucket=bucket-name,S3Key=zip-file-object-key
2.
3.
Write down the function ARN. You will need this in the next section when you add notification
configuration to your Amazon S3 bucket.
(Optional) The preceding 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 \
--region us-west-2 \
--timeout timeout-in-seconds \
--profile adminuser
Note
You can create the Lambda function using the AWS Lambda console, in which case note the
value of the create-function AWS CLI command parameters. You provide the same values
in the console UI.
2.
Follow the steps in the Getting Started to create and invoke the Lambda function at Step 2.2: Invoke
the Lambda Function Manually and Verify Results, Logs, and Metrics (p. 42). For the sample event
for testing, choose S3 Put in Sample event template.
Verify that the thumbnail was created in the target bucket and monitor the activity of your Lambda
function in the AWS Lambda console as follows:
The AWS Lambda console shows a graphical representation of some of the CloudWatch metrics
in the Cloudwatch Metrics at a glance section for your function.
For each graph, you can also click the logs link to view the CloudWatch Logs directly.
Save the following Amazon S3 sample event data in a file and save it as input.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",
139
"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/JRWeUWer
MUE5JgHvANOjpD"
},
"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"
}
}
}
]
}
2.
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 \
--invocation-type Event \
--function-name CreateThumbnail \
--region us-west-2 \
--payload file://file-path/inputfile.txt \
--profile adminuser \
outputfile.txt
Note
You are able to invoke this function because you are using your own credentials to invoke
your own function. In the next section, you configure Amazon S3 to invoke this function on
your behalf, which requires you to add permissions to the access policy associated with
your Lambda function to grant Amazon S3 permissions to invoke your function.
3.
Verify that the thumbnail was created in the target bucket and monitor the activity of your Lambda
function in the AWS Lambda console as follows:
The AWS Lambda console shows a graphical representation of some of the CloudWatch metrics
in the Cloudwatch Metrics at a glance section for your function.
140
For each graph, you can also click the logs link to view the CloudWatch Logs directly.
Next Step
Step 3: Add an Event Source (Configure Amazon S3 to Publish Events) (p. 141)
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 a specific AWS account. If a bucket owner deletes a bucket, some other
AWS account can create a bucket with the same name. This condition ensures that only a specific
AWS account can invoke your Lambda function.
2.
Verify the function's access policy by running the AWS CLI get-policy command.
$ aws lambda get-policy \
--function-name function-name \
--profile adminuser
141
142
role first and then enable it at the time you create the Lambda function. For more information, see Manage
Permissions: Using an IAM Role (Execution Role) (p. 31).
The following diagram illustrates the application flow:
Important
Both the Lambda function and the Amazon Kinesis stream must be in the same AWS region.
This tutorial assumes that you create these resources in the us-west-2 region.
In this tutorial, you use the AWS Command Line Interface to perform AWS Lambda operations such as
creating a Lambda function, creating a stream, and adding records to the stream. You use the AWS
Lambda console to manually invoke the function before you create a Amazon Kinesis stream. You verify
return values and logs in the console UI.
Next Step
Step 1: Prepare (p. 144)
143
Step 1: Prepare
Make sure you have completed the following steps:
Signed up for an AWS account and created an administrator user in the account.
Installed and set up the AWS CLI.
For instructions, see Step 1: Set Up an AWS Account and the AWS CLI (p. 35).
Next Step
Step 2: Create a Lambda Function and Invoke It Manually (Using Sample Event Data) (p. 144)
Note
To see more examples of using other AWS services within your function, including calling
other Lambda functions, see AWS SDK for JavaScript
Create an IAM role (execution role). At the time you upload the deployment package, you need to
specify an IAM role (execution role) that Lambda can assume to execute the function on your behalf.
Create the Lambda function by uploading the deployment package, and then test it by invoking it
manually using sample Amazon Kinesis event data.
Topics
Step 2.1: Create a Deployment Package (p. 144)
Step 2.2: Create the Execution Role (IAM Role) (p. 146)
Step 2.3: Create the Lambda Function and Test It Manually (p. 147)
Node.js
The following is example Node.js code that receives Amazon Kinesis event records as input and processes
them. For illustration, the code writes some of the incoming event data to CloudWatch Logs.
Follow the instructions to create a AWS Lambda function deployment package.
1.
144
event.Records.forEach(function(record) {
// Kinesis data is base64 encoded so decode here
var payload = new Buffer(record.kinesis.data, 'base64').toString('as
cii');
console.log('Decoded payload:', payload);
});
callback(null, "message");
};
Note
The code sample is compliant with the Node.js runtime v4.3. For more information, see
Programming Model (Node.js) (p. 51)
2.
3.
Next Step
Step 2.2: Create the Execution Role (IAM Role) (p. 146)
Java
The following is example Java code that receives Amazon Kinesis event record data as a input and
processes it. For illustration, the code writes some of the incoming event data to CloudWatch Logs.
In the code, recordHandler is the handler. The handler uses the predefined KinesisEvent class that
is defined in the aws-lambda-java-events library.
package example;
import java.io.IOException;
import com.amazonaws.services.lambda.runtime.events.KinesisEvent;
import com.amazonaws.services.lambda.runtime.events.KinesisEvent.KinesisEventRe
cord;
public class ProcessKinesisEvents {
public void recordHandler(KinesisEvent event) throws IOException {
for(KinesisEventRecord rec : event.getRecords()) {
System.out.println(new String(rec.getKinesis().getData().array()));
}
}
}
If the handler returns normally without exceptions, Lambda considers the input batch of records as
processed successfully and begins reading new records in the stream. If the handler throws an exception,
Lambda considers the input batch of records as not processed and invokes the function with the same
batch of records again.
Using the preceding code (in a file named ProcessKinesisEvents.java), create a deployment
package. Make sure that you add the following dependencies:
aws-lambda-java-core
aws-lambda-java-events
145
For more information, see Programming Model for Authoring Lambda Functions in Java (p. 63).
Your deployment package can be a .zip file or a standalone .jar. You can use any build and packaging
tool you are familiar with to create a deployment package. For examples of how to use the Maven build
tool to create a standalone .jar, see Creating a .jar Deployment Package Using Maven without any IDE
(Java) (p. 91) and Creating a .jar Deployment Package Using Maven and Eclipse IDE (Java) (p. 93). For
an example of how to use the Gradle build tool to create a .zip file, see Creating a .zip Deployment
Package (Java) (p. 96).
After you verify that your deployment package is created, go to the next step to create an IAM role
(execution role). You specify this role at the time you create your Lambda function.
Next Step
Step 2.2: Create the Execution Role (IAM Role) (p. 146)
Python
The following is example Python code that receives Amazon Kinesis event record data as input and
processes it. For illustration, the code writes to some of the incoming event data to CloudWatch Logs.
Follow the instructions to create a AWS Lambda function deployment package.
1.
2.
3.
Next Step
Step 2.2: Create the Execution Role (IAM Role) (p. 146)
146
2.
Follow the steps in Creating a Role to Delegate Permissions to an AWS Service in the IAM User
Guide to create an IAM role (execution role). As you follow the steps to create a role, note the
following:
In Role Name, use a name that is unique within your AWS account (for example,
lambda-kinesis-execution-role).
In Select Role Type, choose AWS Service Roles, and then choose AWS Lambda. This grants
the AWS Lambda service permissions to assume the role.
In Attach Policy, choose AWSLambdaKinesisExecutionRole. The permissions in this policy
are sufficient for the Lambda function in this tutorial.
3.
Write down the role ARN. You will need it in the next step when you create your Lambda function.
Next Step
Step 2.3: Create the Lambda Function and Test It Manually (p. 147)
147
Optionally, you can upload the .zip file to an Amazon S3 bucket in the same AWS region, and then specify
the bucket and object name in the preceding command.You need to replace the --zip-file parameter
by the --code parameter, as shown following:
--code S3Bucket=bucket-name,S3Key=zip-file-object-key
Note
You can create the Lambda function using the AWS Lambda console, in which case note the
value of the create-function AWS CLI command parameters. You provide the same values
in the console UI.
2.
Follow the steps in the Getting Started to create and invoke the Lambda function at Step 2.2: Invoke
the Lambda Function Manually and Verify Results, Logs, and Metrics (p. 42). For the sample event
for testing, choose Kinesis in Sample event template.
Verify the results in the console.
2.
148
Note
In this tutorial example, the message is saved in the outputfile.txt file. If you request
synchronous execution (RequestResponse as the invocation type), the function returns
the string message in the response body.
For Node.js, it could be one of the following (whatever one you specify in the code):
context.succeed("message")
context.fail("message")
context.done(null, "message)
For Python or Java, it is the message in the return statement:
return "message"
Next Step
Step 3: Add an Event Source (Create an Amazon Kinesis Stream and Associate It with Your Lambda
Function) (p. 149)
Run the following Amazon Kinesis describe-stream AWS CLI command to get the stream ARN.
$ aws kinesis describe-stream \
--stream-name examplestream \
--region us-west-2 \
--profile adminuser
You need the stream ARN in the next step to associate the stream with your Lambda function. The stream
is of the form:
149
arn:aws:kinesis:aws-region:account-id:stream/stream-name
You can get a list of event source mappings by running the following command.
$ aws lambda list-event-source-mappings \
--region us-west-2 \
--function-name ProcessKinesisRecords \
--event-source kinesis-stream-arn \
--profile adminuser \
--debug
Note
If you disable the event source mapping, AWS Lambda stops polling the Amazon Kinesis stream.
If you re-enable event source mapping, it will resume polling from the sequence number where
it stopped, so each record is processed either before you disabled the mapping or after you
enabled it. If the sequence number falls behind TRIM_HORIZON, when you re-enable it polling
will start from TRIM_HORIZON. However, if you create a new event source mapping, polling will
always start from TRIM_HORIZON or LATEST, depending on the starting position you specify.
This applies even if you delete an event source mapping and create a new one with the same
configuration as the deleted one.
2. AWS Lambda polls the stream and, when it detects updates to the stream, it invokes your Lambda
function by passing in the event data from the stream.
150
AWS Lambda assumes the execution role to poll the stream. You have granted the role permissions
for the necessary Amazon Kinesis actions so that AWS Lambda can poll the stream and read events
from the stream.
3. Your function executes and adds logs to the log group that corresponds to the Lambda function in
Amazon CloudWatch.
The adminuser can also verify the logs reported in the Amazon CloudWatch console. Make sure you
are checking for logs in the same AWS region where you created the Lambda function.
151
Important
Both the Lambda function and the DynamoDB stream must be in the same AWS region. This
tutorial assumes that you create these resources in the us-east-1 region.
In this tutorial, you use the AWS Command Line Interface to perform AWS Lambda operations such as
creating a Lambda function, creating a stream, and adding records to the stream. You use the AWS
Lambda console to manually invoke the function before you create a DynamoDB stream.You verify return
values and logs in the console UI.
Next Step
Step 1: Prepare (p. 153)
152
Step 1: Prepare
Make sure you have completed the following steps:
Signed up for an AWS account and created an administrator user in the account.
Installed and set up the AWS CLI.
For instructions, see Step 1: Set Up an AWS Account and the AWS CLI (p. 35).
Next Step
Step 2: Create a Lambda Function and Invoke It Manually (Using Sample Event Data) (p. 153)
Note
To see more examples of using other AWS services within your function, including calling
other Lambda functions, see AWS SDK for JavaScript
Create an IAM role (execution role). At the time you upload the deployment package, you need to
specify an IAM role (execution role) that Lambda can assume to execute the function on your behalf.
For example, AWS Lambda needs permissions for DynamoDB actions so it can poll the stream and
read records from the stream. In the pull model you must also grant AWS Lambda permissions to
invoke your Lambda function. The example Lambda function writes some of the event data to
CloudWatch, so it needs permissions for necessary CloudWatch actions.
Create the Lambda function by uploading the deployment package, and then test it by invoking it
manually using sample DynamoDB event data.You provide both the deployment package and the IAM
role at the time of creating a Lambda function. You can also specify other configuration information,
such as the function name, memory size, runtime environment to use, and the handler. For more
information about these parameters, see CreateFunction (p. 283). After creating the Lambda function,
you invoke it using sample Amazon DynamoDB event data.
Topics
Step 2.1: Create a Lambda Function Deployment Package (p. 153)
Step 2.2: Create the Execution Role (IAM Role) (p. 155)
Step 2.3: Create the Lambda Function and Test It Manually (p. 156)
Node.js
1.
153
console.log('Loading function');
exports.lambda_handler = function(event, context, callback) {
console.log(JSON.stringify(event, null, 2));
event.Records.forEach(function(record) {
console.log(record.eventID);
console.log(record.eventName);
console.log('DynamoDB Record: %j', record.dynamodb);
});
callback(null, "message");
};
Note
The code sample is compliant with the Node.js runtime v4.3. For more information, see
Programming Model (Node.js) (p. 51)
2.
3.
Next Step
Step 2.2: Create the Execution Role (IAM Role) (p. 155)
Java
In the following code, handleRequest is the handler that AWS Lambda invokes and provides event
data. The handler uses the predefined DynamodbEvent class, which is defined in the
aws-lambda-java-events library.
package example;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.DynamodbEvent;
import com.amazonaws.services.lambda.runtime.events.DynamodbEvent.DynamodbStream
Record;
public class DDBEventProcessor implements
RequestHandler<DynamodbEvent, String> {
public String handleRequest(DynamodbEvent ddbEvent, Context context) {
for (DynamodbStreamRecord record : ddbEvent.getRecords()){
System.out.println(record.getEventID());
System.out.println(record.getEventName());
System.out.println(record.getDynamodb().toString());
}
return "Successfully processed " + ddbEvent.getRecords().size() + "
records.";
}
}
If the handler returns normally without exceptions, Lambda considers the input batch of records as
processed successfully and begins reading new records in the stream. If the handler throws an exception,
154
Lambda considers the input batch of records as not processed and invokes the function with the same
batch of records again.
Using the preceding code (in a file named DDBEventProcessor.java), create a deployment package.
Make sure that you add the following dependencies:
aws-lambda-java-core
aws-lambda-java-events
For more information, see Programming Model for Authoring Lambda Functions in Java (p. 63).
Your deployment package can be a .zip file or a standalone .jar. You can use any build and packaging
tool you are familiar with to create a deployment package. For examples of how to use the Maven build
tool to create a standalone .jar, see Creating a .jar Deployment Package Using Maven without any IDE
(Java) (p. 91) and Creating a .jar Deployment Package Using Maven and Eclipse IDE (Java) (p. 93). For
an example of how to use the Gradle build tool to create a .zip file, see Creating a .zip Deployment
Package (Java) (p. 96).
After you verify that your deployment package is created, go to the next step to create an IAM role
(execution role). You specify this role at the time you create your Lambda function.
Next Step
Step 2.2: Create the Execution Role (IAM Role) (p. 155)
Python
1.
2.
3.
Next Step
Step 2.2: Create the Execution Role (IAM Role) (p. 155)
155
For more information about IAM roles, see IAM Roles in the IAM User Guide. Use the following procedure
to create the IAM role.
2.
Follow the steps in Creating a Role to Delegate Permissions to an AWS Service in the IAM User
Guide to create an IAM role (execution role). As you follow the steps to create a role, note the
following:
In Role Name, use a name that is unique within your AWS account (for example,
lambda-dynamodb-execution-role).
In Select Role Type, choose AWS Service Roles, and then choose AWS Lambda. This grants
the AWS Lambda service permissions to assume the role.
In Attach Policy, choose AWSLambdaDynamoDBExecutionRole. The permissions in this policy
are sufficient for the Lambda function in this tutorial.
3.
Write down the role ARN. You will need it in the next step when you create your Lambda function.
Next Step
Step 2.3: Create the Lambda Function and Test It Manually (p. 156)
156
Note
If you choose Java 8 as the runtime, the handler value must be packageName::methodName.
For more information, see CreateFunction (p. 283). AWS Lambda creates the function and returns function
configuration information.
Optionally, you can upload the .zip file to an Amazon S3 bucket in the same AWS region, and then specify
the bucket and object name in the preceding command.You need to replace the --zip-file parameter
by the --code parameter, as shown following:
--code S3Bucket=bucket-name,S3Key=zip-file-object-key
157
}
},
"NewImage":{
"Message":{
"S":"This item has changed"
},
"Id":{
"N":"101"
}
},
"OldImage":{
"Message":{
"S":"New item!"
},
"Id":{
"N":"101"
}
},
"SequenceNumber":"222",
"SizeBytes":59,
"StreamViewType":"NEW_AND_OLD_IMAGES"
},
"eventSourceARN":"stream-ARN"
},
{
"eventID":"3",
"eventName":"REMOVE",
"eventVersion":"1.0",
"eventSource":"aws:dynamodb",
"awsRegion":"us-east-1",
"dynamodb":{
"Keys":{
"Id":{
"N":"101"
}
},
"OldImage":{
"Message":{
"S":"This item has changed"
},
"Id":{
"N":"101"
}
},
"SequenceNumber":"333",
"SizeBytes":38,
"StreamViewType":"NEW_AND_OLD_IMAGES"
},
"eventSourceARN":"stream-ARN"
}
]
}
2.
158
Note that the invoke command specifies the RequestResponse as the invocation type, which
requests synchronous execution. For more information, see Invoke (p. 304). The function returns the
string message (message in the context.succeed() in the code) in the response body.
3.
Next Step
Step 3: Add an Event Source (Create a DynamoDB Stream and Associate It with Your Lambda
Function) (p. 159)
Sign in to the AWS Management Console and open the DynamoDB console at https://
console.aws.amazon.com/dynamodb/.
In the DynamoDB console, create a table with streams enabled. Make sure you have the US East
(N. Virginia) region selected before you create the table.
Important
You must create a DynamoDB table in the same region where you created the Lambda
function. This tutorial assumes the US East (N. Virginia) region. In addition, both the table
and the Lambda functions must belong to the same AWS account.
159
3.
Write down the stream ARN. You need this in the next step when you associate the stream with your
Lambda function.
Note
This creates a mapping between the specified DynamoDB stream and the Lambda function.
You can associate a DynamoDB stream with multiple Lambda functions, and associate the same
Lambda function with multiple streams. However, the Lambda functions will share the read
throughput for the stream they share.
You can get the list of event source mappings by running the following command.
$ aws lambda list-event-source-mappings \
--region us-east-1 \
--function-name ProcessDynamoDBStream \
--event-source DynamoDB-stream-arn \
--profile adminuser
The list returns all of the event source mappings you created, and for each mapping it shows the
LastProcessingResult, among other things. This field is used to provide an informative message if
there are any problems. Values such as No records processed (indicates that AWS Lambda has not
started polling or that there are no records in the stream) and OK (indicates AWS Lambda successfully
read records from the stream and invoked your Lambda function) indicate that there no issues. If there
are issues, you receive an error message.
160
Note
Amazon S3 can only support one event destination.
For detailed information about how to configure Amazon S3 as the event source, see Using AWS Lambda
with Amazon S3 (p. 125).
The following diagram summarizes the flow:
161
6. If the log includes a record with specific eventType and eventSource values, it publishes the event
to your Amazon SNS topic. In Tutorial: Using AWS Lambda with AWS CloudTrail (p. 162), you subscribe
to the SNS topic using the email protocol, so you get email notifications.
For a tutorial that walks you through an example scenario, see Tutorial: Using AWS Lambda with AWS
CloudTrail (p. 162).
For illustration, the Lambda function notifies you by email if an API call to create an Amazon SNS topic
is reported in the log. That is, when your Lambda function parses the log, it looks for records with the
following:
eventSource = "sns.amazonaws.com"
eventName = "CreateTopic"
If found, it publishes the event to your Amazon SNS topic (you configure this topic to notify you by email).
162
Implementation Summary
Upon completing this tutorial, you will have Amazon S3, AWS Lambda, Amazon SNS, and AWS Identity
and Access Management (IAM) resources in your account:
Note
This tutorial assumes that you create these resources in the us-west-2 region.
In Lambda:
A Lambda function.
An access policy associated with your Lambda function You grant Amazon S3 permissions to invoke
the Lambda function using this permissions policy.You will also restrict the permissions so that Amazon
S3 can invoke the Lambda function only for object-created events from a specific bucket that is owned
by a specific AWS account.
Note
It is possible for an AWS account to delete a bucket and some other AWS account to later
create a bucket with same name. The additional conditions ensure that Amazon S3 can invoke
the Lambda function only if Amazon S3 detects object-created events from a specific bucket
owned by a specific AWS account.
For more information, see How It Works (p. 3).
In IAM:
An IAM role (execution role) You grant permissions that your Lambda function needs through the
permissions policy associated with this role.
In Amazon S3:
A bucket In this tutorial, the bucket name is examplebucket. When you turn the trail on in the
CloudTrail console, you specify this bucket for CloudTrail to save the logs.
Notification configuration on the examplebucket In the configuration, you direct Amazon S3 to
publish object-created events to Lambda, by invoking your Lambda function. For more information
about the Amazon S3 notification feature, see Setting Up Notification of Bucket Events in Amazon
Simple Storage Service Developer Guide.
Sample CloudTrail log object (ExampleCloudTrailLog.json) in examplebucket bucket In the
first half of this exercise, you create and test your Lambda function by manually invoking it using a
sample S3 event. This sample event identifies examplebucket as the bucket name and this sample
object key name. Your Lambda function then reads the object and sends you email notifications using
an SNS topic.
In Amazon SNS
An SNS topic You subscribe to this topic by specifying email as the protocol.
Now you are ready to start the tutorial.
Next Step
Step 1: Prepare (p. 164)
163
Step 1: Prepare
In this section you do the following:
Sign up for an AWS account and set up the AWS CLI.
Turn on CloudTrail in your account.
Create an SNS topic and subscribe to it.
Follow the steps in the following sections to walk through the setup process.
Note
In this tutorial, we assume that you are setting the resources in the us-west-2 region.
Step 1.1: Sign Up for AWS and Set Up the AWS CLI
Make sure you have completed the following steps:
Signed up for an AWS account and created an administrator user in the account (called adminuser).
Installed and set up the AWS CLI.
For instructions, see Step 1: Set Up an AWS Account and the AWS CLI (p. 35).
Note
Although you turn CloudTrail on now, you do not perform any additional configuration for your
Lambda function to process the real CloudTrail logs in the first half of this exercise. Instead, you
will use sample CloudTrail log objects (that you will upload) and sample S3 events to manually
invoke and test your Lambda function. In the second half of this tutorial, you perform additional
configuration steps that enable your Lambda function to process the CloudTrail logs.
2.
For instructions, see Create a Topic in the Amazon Simple Notification Service Developer Guide.
Subscribe to the topic by providing an email address as the endpoint.
3.
For instructions, see Subscribe to a Topic in the Amazon Simple Notification Service Developer
Guide.
Note down the topic ARN. You will need the value in the following sections.
Next Step
Step 2: Create a Lambda Function and Invoke It Manually (Using Sample Event Data) (p. 165)
164
Note
Your Lambda function uses an S3 event that provides the bucket name and key name of the
object CloudTrail created. Your Lambda function then reads that object to process CloudTrail
records.
Create an IAM role (execution role). At the time you upload the deployment package, you need to
specify an IAM role (execution role) that Lambda can assume to execute the function on your behalf.
Create the Lambda function by uploading the deployment package, and then test it by invoking it
manually using sample CloudTrail event data.
Topics
Step 2.1: Create a Deployment Package (p. 165)
Step 2.2: Create the Execution Role (IAM Role) (p. 167)
Step 2.3: Create the Lambda Function and Test It Manually (p. 168)
Node.js
1.
EVENT_SOURCE_TO_TRACK
EVENT_NAME_TO_TRACK
DEFAULT_SNS_REGION =
SNS_TOPIC_ARN
=
= /sns.amazonaws.com/;
= /CreateTopic/;
'us-west-2';
'The ARN of your SNS topic';
165
async.waterfall([
function fetchLogFromS3(next){
console.log('Fetching compressed log from S3...');
s3.getObject({
Bucket: srcBucket,
Key: srcKey
},
next);
},
function uncompressLog(response, next){
console.log("Uncompressing log...");
zlib.gunzip(response.Body, next);
},
function publishNotifications(jsonBuffer, next) {
console.log('Filtering log...');
var json = jsonBuffer.toString();
console.log('CloudTrail JSON from S3:', json);
var records;
try {
records = JSON.parse(json);
} catch (err) {
next('Unable to parse CloudTrail JSON: ' + err);
return;
}
var matchingRecords = records
.Records
.filter(function(record) {
return record.eventSource.match(EVENT_SOURCE_TO_TRACK)
&& record.eventName.match(EVENT_NAME_TO_TRACK);
});
console.log('Publishing ' + matchingRecords.length + ' notific
ation(s) in parallel...');
async.each(
matchingRecords,
function(record, publishComplete) {
console.log('Publishing notification: ', record);
sns.publish({
Message:
'Alert... SNS topic created: \n TopicARN=' +
record.responseElements.topicArn + '\n\n' +
JSON.stringify(record),
TopicArn: SNS_TOPIC_ARN
}, publishComplete);
},
next
);
}
], function (err) {
if (err) {
console.error('Failed to publish notifications: ', err);
} else {
console.log('Successfully published all notifications.');
}
callback(null,"message");
});
};
166
Note
The code sample is compliant with the Node.js runtime v4.3. For more information, see
Programming Model (Node.js) (p. 51)
2.
3.
Note
We're using Node.js in this tutorial example, but you can author your Lambda functions in Java
or Python too.
Next Step
Step 2.2: Create the Execution Role (IAM Role) (p. 167)
In the navigation pane of the IAM console, choose Policies, and then choose Create Policy.
Next to Copy an AWS Managed Policy, choose Select.
Next to AWSLambdaExecute, choose Select.
Copy the following policy into the Policy Document, replacing the existing policy, and then
update the policy with the ARN of the Amazon SNS topic that you created.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:*"
],
"Resource": "arn:aws:logs:*:*:*"
},
{
"Effect": "Allow",
"Action": [
"s3:GetObject"
],
"Resource": "arn:aws:s3:::examplebucket/*"
167
},
{
"Effect": "Allow",
"Action": [
"sns:Publish"
],
"Resource": "your sns topic ARN"
}
]
}
3.
Note the permissions policy name because you will use it in the next step.
4.
Follow the steps in Creating a Role to Delegate Permissions to an AWS Service in the IAM User
Guide to create an IAM role and then attach the permissions policy you just created to the role. As
you follow the steps to create a role, note the following:
In Role Name, use a name that is unique within your AWS account (for example,
lambda-cloudtrail-execution-role).
In Select Role Type, choose AWS Service Roles, and then choose AWS Lambda.
In Attach Policy, choose the policy you created in the previous step.
Next Step
Step 2.3: Create the Lambda Function and Test It Manually (p. 168)
Step 2.3.1: Create the Lambda Function (Upload the Deployment Package)
In this step, you upload the deployment package using the AWS CLI and provide configuration information
when you create the Lambda function. At the command prompt, run the following Lambda CLI
create-function command using the adminuser profile.
Note
You need to update the command by providing the .zip file path
(//file-path/CloudTrailEventProcessing.zip \) and the execution role ARN
(execution-role-arn). If you used the sample code provided earlier in this tutorial, set the
--runtime parameter value to node.js.
You can author your Lambda functions in Java or Python too. If you use another language,
change the --runtime parameter value to java8 or python2.7 as needed.
168
Optionally, you can upload the .zip file to an Amazon S3 bucket in the same AWS region, and then specify
the bucket and object name in the preceding command.You need to replace the --zip-file parameter
by the --code parameter as shown:
--code S3Bucket=bucket-name,S3Key=zip-file-object-key
Note
You can create the Lambda function using the AWS Lambda console, in which case note the
value of the create-function AWS CLI command parameters. You provide the same values
in the console.
Note
Note that one of events in this log has sns.amazonaws.com as the eventSource and
CreateTopic as the eventName. Your Lambda function reads the logs and if it finds an
event of this type, it publishes the event to the Amazon SNS topic that you created and then
you receive one email when you invoke the Lambda function manually.
{
"Records":[
{
"eventVersion":"1.02",
"userIdentity":{
"type":"Root",
"principalId":"account-id",
"arn":"arn:aws:iam::account-id:root",
"accountId":"account-id",
"accessKeyId":"access-key-id",
"sessionContext":{
"attributes":{
"mfaAuthenticated":"false",
"creationDate":"2015-01-24T22:41:54Z"
}
}
},
169
"eventTime":"2015-01-24T23:26:50Z",
"eventSource":"sns.amazonaws.com",
"eventName":"CreateTopic",
"awsRegion":"us-west-2",
"sourceIPAddress":"205.251.233.176",
"userAgent":"console.amazonaws.com",
"requestParameters":{
"name":"dropmeplease"
},
"responseElements":{
"topicArn":"arn:aws:sns:us-west-2:account-id:exampletopic"
},
"requestID":"3fdb7834-9079-557e-8ef2-350abc03536b",
"eventID":"17b46459-dada-4278-b8e2-5a4ca9ff1a9c",
"eventType":"AwsApiCall",
"recipientAccountId":"account-id"
},
{
"eventVersion":"1.02",
"userIdentity":{
"type":"Root",
"principalId":"account-id",
"arn":"arn:aws:iam::account-id:root",
"accountId":"account-id",
"accessKeyId":"access-key-id",
"sessionContext":{
"attributes":{
"mfaAuthenticated":"false",
"creationDate":"2015-01-24T22:41:54Z"
}
}
},
"eventTime":"2015-01-24T23:27:02Z",
"eventSource":"sns.amazonaws.com",
"eventName":"GetTopicAttributes",
"awsRegion":"us-west-2",
"sourceIPAddress":"205.251.233.176",
"userAgent":"console.amazonaws.com",
"requestParameters":{
"topicArn":"arn:aws:sns:us-west-2:account-id:exampletopic"
},
"responseElements":null,
"requestID":"4a0388f7-a0af-5df9-9587-c5c98c29cbec",
"eventID":"ec5bb073-8fa1-4d45-b03c-f07b9fc9ea18",
"eventType":"AwsApiCall",
"recipientAccountId":"account-id"
}
]
}
2.
Run the gzip command to create a .gz file from the preceding source file.
$ gzip ExampleCloudTrailLog.json
170
3.
4.
5.
In the AWS Management Console, invoke the function manually using sample Amazon S3 event
data. For instructions, see the Getting Started exercise Step 2.2: Invoke the Lambda Function Manually
and Verify Results, Logs, and Metrics (p. 42). In the console, use the following sample Amazon S3
event data.
171
Note
We recommend that you invoke the function using the console because the console UI
provides a user-friendly interface for reviewing the execution results, including the execution
summary, logs written by your code, and the results returned by the function (because the
console always performs synchronous executioninvokes the Lambda function using the
RequestResponse invocation type).
{
"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/JR
WeUWerMUE5JgHvANOjpD"
},
"s3":{
"s3SchemaVersion":"1.0",
"configurationId":"testConfigRule",
"bucket":{
"name":"your bucket name",
"ownerIdentity":{
"principalId":"A3NL1KOZZKExample"
},
"arn":"arn:aws:s3:::mybucket"
},
"object":{
"key":"ExampleCloudTrailLog.json.gz",
"size":1024,
"eTag":"d41d8cd98f00b204e9800998ecf8427e",
"versionId":"096fKKXTRTtl3on89fVO.nfljtsv6qko"
}
}
}
]
}
6.
Execute the following AWS CLI command to invoke the function manually using the adminuser
profile.
$
172
Because your example log object has an event record showing the SNS API to call to create a topic,
the Lambda function posts that event to your SNS topic, and you should get an email notification.
7.
You can monitor the activity of your Lambda function by using CloudWatch metrics and logs. For
more information about CloudWatch monitoring, see Troubleshooting and Monitoring AWS Lambda
Functions with Amazon CloudWatch (p. 118).
(Optional) Manually invoke the Lambda function using AWS CLI as follows:
a.
Save the JSON from Step 2 earlier in this procedure to a file called input.txt.
b.
Note
In this tutorial example, the message is saved in the outputfile.txt file. If you
request synchronous execution (RequestResponse as the invocation type), the function
returns the string message in the response body.
For Node.js, it could be one of the following (whatever one you specify in the code):
context.succeed("message")
context.fail("message")
context.done(null, "message)
For Python or Java, it is the message in the return statement:
return "message"
Next Step
Step 3: Add Event Source (Configure Amazon S3 to Publish Events) (p. 173)
173
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 a specific AWS account. If a bucket owner deletes a bucket, some other
AWS account can create a bucket with the same name. This condition ensures that only a specific
AWS account can invoke your Lambda function.
2.
Verify the function's access policy by running the AWS CLI get-policy command.
$ aws lambda get-policy \
--function-name function-name \
--profile adminuser
For example, the function CloudTrailEventProcessing created in us-west-2 region has the following
ARN:
arn:aws:lambda:us-west-2:account-id:function:CloudTrailEventProcessing
For instructions on adding notification configuration to a bucket, see Enabling Event Notifications in the
Amazon Simple Storage Service Console User Guide.
174
175
Third, you grant permissions from each account in order for the Lambda function to subscribe to the
Amazon SNS topic. Then, you test the end-to-end setup.
Important
This tutorial assumes that you create these resources in the us-east-1 region.
In this tutorial, you use the AWS Command Line Interface to perform AWS Lambda operations such as
creating a Lambda function, creating an Amazon SNS topic and granting permissions to allow these two
resources to access each other.
Next Step
Step 1: Prepare (p. 176)
Step 1: Prepare
Sign up for an AWS account and create an administrator user in the account (called adminuser).
Install and set up the AWS CLI.
For instructions, see Step 1: Set Up an AWS Account and the AWS CLI (p. 35).
Next Step
Step 2: Create a Lambda Function (p. 176)
Node.js
1.
176
Note
The code sample is compliant with the Node.js runtime v4.3. For more information, see
Programming Model (Node.js) (p. 51)
2.
3.
Next Step
Step 2.2: Create the Execution Role (IAM Role) (p. 178)
Java
Open a text editor, and then copy the following code.
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(Cal
endar.getInstance().getTime());
context.getLogger().log("Invocation started: " + timeStamp);
context.getLogger().log(request.getRecords().get(0).getSNS().getMes
sage());
timeStamp = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss").format(Calendar.get
Instance().getTime());
context.getLogger().log("Invocation completed: " + timeStamp);
return null;
}
}
Using the preceding code (in a file named LambdaWithSNS.java), create a deployment package. Make
sure that you add the following dependencies:
aws-lambda-java-core
aws-lambda-java-events
For more information, see Programming Model for Authoring Lambda Functions in Java (p. 63).
177
Your deployment package can be a .zip file or a standalone .jar. You can use any build and packaging
tool you are familiar with to create a deployment package. For examples of how to use the Maven build
tool to create a standalone .jar, see Creating a .jar Deployment Package Using Maven without any IDE
(Java) (p. 91) and Creating a .jar Deployment Package Using Maven and Eclipse IDE (Java) (p. 93). For
an example of how to use the Gradle build tool to create a .zip file, see Creating a .zip Deployment
Package (Java) (p. 96).
After you verify that your deployment package is created, go to the next step to create an IAM role
(execution role). You specify this role at the time you create your Lambda function.
Next Step
Step 2.2: Create the Execution Role (IAM Role) (p. 178)
Python
1.
2.
3.
Next Step
Step 2.2: Create the Execution Role (IAM Role) (p. 178)
178
In Select Role Type, choose AWS Service Roles, and then choose AWS Lambda. This grants
the AWS Lambda service permissions to assume the role.
In Attach Policy, choose AWSLambdaBasicExecutionRole. The permissions in this policy are
sufficient for the Lambda function in this tutorial.
3.
Write down the role ARN. You will need it in the next step when you create your Lambda function.
Note the topic arn that is returned by the command. You will need it when you add permissions to the
Lambda function to subscribe to the topic.
2. From account B, create the Lambda function. For the runtime parameter, select either nodejs4.3,
python2.7 or java8, depending on the code sample you selected when you created your deployment
package.
aws lambda create-function \
--function-name SNS-X-Account \
--runtime runtime language \
--role role arn \
--handler index.handler \
--description "SNS X Account Test Function" \
--timeout 60 \
--memory-size 128 \
--zip-file fileb://path/LambdaWithSNS.zip
Note the function arn that is returned by the command. You will need it when you add permissions to
allow Amazon SNS to invoke your function.
3. From account A add permission to account B to subscribe to the topic:
aws sns add-permission \
--region us-east-1 \
--topic-arn Amazon SNS topic arn \
--label lambda-access \
--aws-account-id B \
--action-name Subscribe ListSubscriptionsByTopic Receive
4. From account B add the Lambda permission to allow invocation from Amazon SNS:
aws lambda add-permission \
--function-name SNS-X-Account \
--statement-id sns-x-account \
--action "lambda:InvokeFunction" \
--principal sns.amazonaws.com \
--source-arn Amazon SNS topic arn
179
In response, Lambda returns the following JSON code. The Statement value is a JSON string version
of the statement added to the Lambda function policy:
{
"Statement": "{\"Condition\":{\"Arn
Like\":{\"AWS:SourceArn\":\"arn:aws:lambda:us-east-1:B:function:SNS-X-Ac
count\"}},\"Action\":[\"lambda:InvokeFunction\"],\"Re
source\":\"arn:aws:lambda:us-east-1:A:function:SNS-X-Account\",\"Effect\":\"Al
low\",\"Principal\":{\"Service\":\"sns.amazonaws.com\"},\"Sid\":\"sns-x-ac
count1\"}"
}
Note
Do not use the --source-account parameter to add a source account to the Lambda policy
when adding the policy. Source account is not supported for Amazon SNS event sources and
will result in access being denied.This has no security impact as the source account is included
in the source ARN.
5. From account B subscribe the Lambda function to the topic:
aws sns subscribe \
--topic-arn Amazon SNS topic arn \
--protocol lambda \
--notification-endpoint arn:aws:lambda:us-east-1:B:function:SNS-X-Account
6. From account A you can now test the subscription. Type "Hello World" into a text file and save it as
message.txt. Then run the following command:
aws sns publish \
--topic-arn arn:aws:sns:us-east-1:A:lambda-x-account \
--message file://message.txt \
--subject Test
This will return a message id with a unique identifier, indicating the message has been accepted by
the Amazon SNS service. Amazon SNS will then attempt to deliver it to the topic's subscribers.
Note
Alternatively, you could supply a JSON string directly to the message parameter, but using a
text file allows for line breaks in the message.
For more information on Amazon SNS, see What is Amazon Simple Notification Service?
180
181
The POST method on the DynamoDBManager resource supports the following DynamoDB operations:
Create, update, and delete an item.
Read an item.
Scan an item.
Other operations (echo, ping), not related to DynamoDB, that you can use for testing.
The request payload you send in the POST request identifies the DynamoDB operation and provides
necessary data. For example:
The following is a sample request payload for a DynamoDB put item operation:
{
"operation": "create",
"tableName": "LambdaTable",
"payload": {
"Item": {
"Id": "1",
"name": "Bob"
}
}
}
The following is a sample request payload for a DynamoDB read item operation:
{
"operation": "read",
"tableName": "LambdaTable",
"payload": {
"Key": {
"Id": "1"
}
}
}
The following is a sample request payload for a the echo operation. You will then send HTTPS PUT
request to the endpoint, using the following data in the request body.
{
"operation": "echo",
"payload": {
"somekey1": "somevalue1",
"somekey2": "somevalue2"
}
}
You can also create and manage API endpoints from the AWS Lambda console. For example, search
for the microservice in the blueprints. This tutorial does not use the console, instead it uses AWS CLI
to provide you with more details of how the API works.
182
Next Step
Step 1: Prepare (p. 183)
Step 1: Prepare
Make sure you have completed the following steps:
Signed up for an AWS account and created an administrator user in the account.
Installed and set up the AWS CLI.
For instructions, see Step 1: Set Up an AWS Account and the AWS CLI (p. 35).
Important
This example uses the us-east-1 region to create an API using Amazon API Gateway and a
Lambda function.
Next Step
Step 2: Create a Lambda Function and Test It Manually (p. 183)
Node.js
Follow the instructions to create a AWS Lambda function deployment package.
1.
183
*
*
- operation: one of the operations in the switch statement below
*
- tableName: required for operations that interact with DynamoDB
*
- payload: a parameter to pass to the operation being performed
*/
exports.handler = function(event, context, callback) {
//console.log('Received event:', JSON.stringify(event, null, 2));
var operation = event.operation;
if (event.tableName) {
event.payload.TableName = event.tableName;
}
switch (operation) {
case 'create':
dynamo.put(event.payload, callback);
break;
case 'read':
dynamo.get(event.payload, callback);
break;
case 'update':
dynamo.update(event.payload, callback);
break;
case 'delete':
dynamo.delete(event.payload, callback);
break;
case 'list':
dynamo.scan(event.payload, callback);
break;
case 'echo':
callback(null, "Success");
break;
case 'ping':
callback(null, "pong");
break;
default:
callback('Unknown operation: ${operation}');
}
};
Note
The code sample is compliant with the Node.js runtime v4.3. For more information, see
Programming Model (Node.js) (p. 51)
2.
3.
Next Step
Step 2.2: Create the Execution Role (IAM Role) (p. 185)
Python
Follow the instructions to create AWS Lambda function deployment package.
1.
184
2.
3.
Next Step
Step 2.2: Create the Execution Role (IAM Role) (p. 185)
185
2.
Follow the steps in Creating a Role to Delegate Permissions to an AWS Service in the IAM User
Guide to create an IAM role (execution role). As you follow the steps to create a role, note the
following:
In Role Name, use a name that is unique within your AWS account (for example,
lambda-gateway-execution-role).
In Select Role Type, choose AWS Service Roles, and then choose AWS Lambda. This grants
the AWS Lambda service permissions to assume the role.
You create an IAM role without attaching a permissions policy in the console. After you create the
role, you update the role, and then attach the following permissions policy to the role.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "Stmt1428341300017",
"Action": [
"dynamodb:DeleteItem",
"dynamodb:GetItem",
"dynamodb:PutItem",
"dynamodb:Query",
"dynamodb:Scan",
"dynamodb:UpdateItem"
],
"Effect": "Allow",
"Resource": "*"
},
{
"Sid": "",
"Resource": "*",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Effect": "Allow"
}
]
}
3.
Write down the role ARN (Amazon Resource Name). You need it in the next step when you create
your Lambda function.
Next Step
Step 2.3: Create the Lambda Function and Test It Manually (p. 186)
186
Optionally, you can upload the .zip file to an Amazon S3 bucket in the same AWS region, and then specify
the bucket and object name in the preceding command.You need to replace the --zip-file parameter
by the --code parameter, as shown following:
--code S3Bucket=bucket-name,S3Key=zip-file-object-key
Note
You can create the Lambda function using the AWS Lambda console, in which case note the
value of the create-function AWS CLI command parameters. You provide the same values
in the console UI.
Follow the steps in the Getting Started exercise to create and invoke the Lambda function at Step
2.2: Invoke the Lambda Function Manually and Verify Results, Logs, and Metrics (p. 42). For the
sample event for testing, choose Hello World in Sample event template, and then replace the data
using the following:
{
"operation": "echo",
"payload": {
"somekey1": "somevalue1",
"somekey2": "somevalue2"
187
}
}
2.
To test one of the dynamo operations, such as read, change the input data to the following:
{
"operation": "read",
"tableName": "the name of your stream table"
"payload": {
"Key": {
"the primary key of the table": "the value of the key"
}
}
}
3.
2.
Note
In this tutorial example, the message is saved in the outputfile.txt file if you request
synchronous execution (RequestResponse as the invocation type). The function returns
the string message in the response body. If you use the Event invocation type, no message
is returned to the output file. In either case, the outputfile.txt parameter is required.
For Node.js, it could be one of the following (whatever one you specify in the code):
context.succeed("message")
context.fail("message")
context.done(null, "message)
For Python or Java, it is the message in the return statement:
return "message"
188
Next Step
Step 3: Create an API Using Amazon API Gateway and Test It (p. 189)
The following is example response (at this time you only have the root resource, but you add more
resources in the next step):
{
"items": [
{
"path": "/",
"id": "root-id"
}
]
}
189
Note the ID in the response. This is the ID of the resource (DynamoDBManager) that you created.
We specify NONE for the --authorization-type parameter, which means that unauthenticated requests
for this method are supported. This is fine for testing but in production you should use either the key-based
or role-base authentication.
The following is an example response:
{
"apiKeyRequired": false,
"httpMethod": "POST",
"authorizationType": "NONE"
}
Step 3.4: Set the Lambda Function as the Destination for the POST Method
Run the following command to set the Lambda function as the integration point for the POST method (this
is the method Amazon API Gateway invokes when you make an HTTPS request for the POST method
endpoint).
$ aws apigateway put-integration \
--rest-api-id api-id \
--resource-id resource-id \
--http-method POST \
--type AWS \
--integration-http-method POST \
--uri arn:aws:apigateway:aws-region:lambda:path/2015-03-31/func
tions/arn:aws:lambda:aws-region:aws-acct-id:function:your-lambda-functionname/invocations
190
Note
--rest-api-id is the ID of the API (DynamoDBOperations) that you created in Amazon
API Gateway.
--resource-id is the resource ID of the resource (DynamoDBManager) you created in the
API
--http-method is the API Gateway method and --integration-http-method is the
method that API Gateway uses to communicate with AWS Lambda.
--uri is unique identifier for the endpoint to which Amazon API Gateway can send request.
The following is an example response:
{
"httpMethod": "POST",
"type": "AWS",
"uri": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/func
tions/arn:aws:lambda:us-east-1:aws-acct-id:function:LambdaFunctionForAPIGate
way/invocations",
"cacheNamespace": "resource-id"
}
Set content-type of the POST method response and integration response to JSON as follows:
Run the following command to set the POST method response to JSON. This is the response type that
your API method returns.
$ aws apigateway put-method-response \
--rest-api-id api-id \
--resource-id resource-id \
--http-method POST \
--status-code 200 \
--response-models "{\"application/json\": \"Empty\"}"
Run the following command to set the POST method integration response to JSON. This is the response
type that Lambda function returns.
$ aws apigateway put-integration-response \
--rest-api-id api-id \
--resource-id resource-id \
--http-method POST \
--status-code 200 \
--response-templates "{\"application/json\": \"\"}"
191
Step 3.6: Grant Permissions that Allows Amazon API Gateway to Invoke
the Lambda Function
Now that you have an API created using Amazon API Gateway and you've deployed it, you can test.
First, you need to add permissions so that Amazon API Gateway can invoke your Lambda function when
you send HTTPS request to the POST method.
To do this, you need to add a permissions to the permissions policy associated with your Lambda function.
Run the following add-permission AWS Lambda command to grant the Amazon API Gateway service
principal (apigateway.amazonaws.com) permissions to invoke your Lambda function
(LambdaFunctionForAPIGateway).
$ aws lambda add-permission \
--function-name LambdaFunctionOverHttps \
--statement-id apigateway-test-2 \
--action lambda:InvokeFunction \
--principal apigateway.amazonaws.com \
--source-arn "arn:aws:execute-api:us-east-1:aws-acct-id:api-id/*/POST/DynamoDB
Manager"
You must grant this permission to enable testing (if you go to the Amazon API Gateway and choose Test
to test the API method, you need this permission). Note the --source-arn specifies a wildcard character
(*) as the stage value (indicates testing only). This allows you to test without deploying the API.
Now, run the same command again, but this time you grant to your deployed API permissions to invoke
the Lambda function.
$ aws lambda add-permission \
--function-name LambdaFunctionOverHttps \
--statement-id apigateway-prod-2 \
--action lambda:InvokeFunction \
--principal apigateway.amazonaws.com \
--source-arn "arn:aws:execute-api:us-east-1:aws-acct-id:api-id/prod/POST/DynamoD
BManager"
You grant this permission so that your deployed API has permissions to invoke the Lambda function.
Note that the --source-arn specifies a prod which is the stage name we used when deploying the
API.
192
You can use Amazon API Gateway CLI commands to send an HTTPS POST request to the resource
(DynamoDBManager) endpoint. Because you deployed your Amazon API Gateway, you can use Curl to
invoke the methods for the same operation.
The Lambda function supports using the create operation to create an item in your DynamoDB table.
To request this operation, use the following JSON:
{
"operation": "create",
"tableName": "LambdaTable",
"payload": {
"Item": {
"Id": "foo",
"number": 5
}
}
}
Run the test-invoke-method Amazon API Gateway command to send an HTTPS POST method
request to the resource (DynamoDBManager) endpoint with the preceding JSON in the request body.
$ aws apigateway test-invoke-method \
--rest-api-id api-id \
--resource-id resource-id \
--http-method POST \
--path-with-query-string "" \
--body "{\"operation\":\"create\",\"tableName\":\"LambdaTable\",\"pay
load\":{\"Item\":{\"Id\":\"1\",\"name\":\"Bob\"}}}"
To send request for the echo operation that your Lambda function supports, you can use the following
request payload:
{
"operation": "echo",
"payload": {
"somekey1": "somevalue1",
"somekey2": "somevalue2"
}
}
Run the test-invoke-method Amazon API Gateway CLI command to send an HTTPS POST method
request to the resource (DynamoDBManager) endpoint using the preceding JSON in the request body.
$ aws apigateway test-invoke-method \
--rest-api-id api-id \
--resource-id resource-id \
--http-method POST \
193
--path-with-query-string "" \
--body "{\"operation\":\"echo\",\"payload\":{\"somekey1\":\"some
value1\",\"somekey2\":\"somevalue2\"}}"
Note
You can also invoke your Lambda function over HTTP using Amazon API Gateway (instead of
using any of the AWS SDKs). Amazon API Gateway adds an additional layer between your
mobile users and your app logic that enable the following:
Ability to throttle individual users or requests.
Protect against Distributed Denial of Service attacks.
Provide a caching layer to cache response from your Lambda function.
Note the following about how the mobile application and AWS Lambda integration works:
Push-event model This is a model (see Event Source Mapping (p. 10)), where the app invokes the
Lambda function by passing the event data as parameter.
Synchronous or asynchronous invocation The app can invoke the Lambda function and get a
response back in real time by specifying RequestResponse as the invocation type (or use the Event
invocation type for asynchronous invocation). For information about invocation types, see Manage
Permissions: Using a Lambda Function Policy (p. 32).
Event structure The event your Lambda function receives is defined by your application, and your
Lambda function is the custom code written to process the specific event type.
Note that there are two types of permissions policies that you work with in setting the end-to-end
experience:
Permissions for your Lambda function Regardless of what invokes a Lambda function, AWS
Lambda executes the function by assuming the IAM role (execution role) that you specify at the time
you create the Lambda function. Using the permissions policy associated with this role, you grant your
Lambda function the permissions that it needs. For example, if your Lambda function needs to read
an object, you grant permissions for the relevant Amazon S3 actions in the permissions policy. For
more information, see Manage Permissions: Using an IAM Role (Execution Role) (p. 31).
194
Permissions for the mobile app to invoke your Lambda function The application must have valid
security credentials and permissions to invoke a Lambda function. For mobile applications, you can
use the Amazon Cognito service to manage user identities, authentication, and permissions.
The following diagram illustrates the application flow (the illustration assumes a mobile app using AWS
Mobile SDK for Android to make the API calls):
1. The mobile application sends a request to Amazon Cognito with an identity pool ID in the request (you
create the identity pool as part the setup).
2. Amazon Cognito returns temporary security credentials back to the application.
Amazon Cognito assumes the role associated with the identity pool to generate temporary credentials.
What the application can do using the credentials is limited to the permissions defined in the permissions
policy associated with the role Amazon Cognito used in obtaining the temporary credential.
Note
The AWS SDK can cache the temporary credentials so that the application does not send a
request to Amazon Cognito each time it needs to invoke a Lambda function.
3. The mobile application invokes the Lambda function using temporary credentials (Cognito Identity).
4. AWS Lambda assumes the execution role to execute your Lambda function on your behalf.
5. The Lambda function executes.
6. AWS Lambda returns results to the mobile application, assuming the app invoked the Lambda function
using the RequestResponse invocation type (synchronous invocation).
For a tutorial that walks you through an example setup, see Tutorial: Using AWS Lambda as Mobile
Application Backend (p. 195).
195
The sample mobile application will generate event data consisting of a name (first name and last name)
in this format:
{ firstName: 'value1', lastName: 'value2' }
You use Lambda function to process the event.That is, the app (using the AWS Mobile SDK for Android)
invokes a Lambda function (ExampleAndroidEventProcessor) by passing the event data to it. The
Lambda function in this tutorial does the following:
Logs incoming event data to Amazon CloudWatch Logs.
Upon successful execution, returns a simple string in the response body. Your mobile app displays
the message using the Android Toast class.
Note
The way that the mobile application invokes a Lambda function as shown in this tutorial is an
example of the AWS Lambda request-response model in which an application invokes a Lambda
function and then receives a response in real time. For more information, see Programming
Model (p. 51).
Implementation Summary
The tutorial is divided into two main sections:
First, you perform the necessary setup to create a Lambda function and test it by invoking it manually
using sample event data (you don't need mobile app to test your Lambda function).
Second, you create an Amazon Cognito identity pool to manage authentication and permissions, and
create the example Android application. Then, you run the application and it invokes the Lambda
function. You can then verify the end-to-end experience. In this tutorial example:
You use the Amazon Cognito service to manage user identities, authentication, and permissions.
The mobile application must have valid security credentials and permissions to invoke a Lambda
function. As part of the application setup, you create an Amazon Cognito identity pool to store user
identities and define permissions. For more information, see Amazon Cognito
This mobile application does not require its users to log in. A mobile application can require its users
to log in using public identity providers such as Amazon and Facebook. The scope of this tutorial is
limited and assumes that the mobile application users are unauthenticated. Therefore, when you
configure Amazon Cognito identity pool you will do the following:
Enable access for unauthenticated identities.
Amazon Cognito provides a unique identifier and temporary AWS credentials for these users to
invoke the Lambda function.
In the access permissions policy associated with the IAM role for unauthenticated users, add
permissions to invoke the Lambda function. An identity pool has two associated IAM roles, one
for authenticated and one for unauthenticated application users. In this example, Amazon Cognito
assumes the role for unauthenticated users to obtain temporary credentials. When the app uses
these temporary credentials to invoke your Lambda function, it can do so only if has necessary
permissions (that is, credentials may be valid, but you also need permissions). You do this by
updating the permissions policy that Amazon Cognito uses to obtain the temporary credentials.
The following diagram illustrates the application flow:
196
Next Step
Step 1: Prepare (p. 197)
Step 1: Prepare
Make sure you have completed the following steps:
Signed up for an AWS account and created an administrator user in the account.
Installed and set up the AWS CLI.
For instructions, see Step 1: Set Up an AWS Account and the AWS CLI (p. 35).
Note
The tutorial creates a Lambda function and an Amazon Cognito identity pool in the us-east-1
region. If you want to use a different AWS region, you must create these resources in the same
region. You also need to update the example mobile application code by providing the specific
region that you want to use.
Next Step
Step 2: Create the Lambda Function and Invoke It Manually (Using Sample Event Data) (p. 197)
Note
To see more examples of using other AWS services within your function, including calling
other Lambda functions, see AWS SDK for JavaScript
197
Create an IAM role (execution role). At the time you upload the deployment package, you need to
specify an IAM role (execution role). This is the role that AWS Lambda assumes to invoke your Lambda
function on your behalf.
Create the Lambda function by uploading the deployment package, and then test it by invoking it
manually using sample event data.
Topics
Step 2.1: Create a Deployment Package (p. 198)
Step 2.2: Create the Execution Role (IAM Role) (p. 200)
Step 2.3: Create the Lambda Function and Invoke It Manually (Using Sample Event Data) (p. 201)
Node.js
Follow the instructions to create a AWS Lambda function deployment package.
1.
Note
The code sample is compliant with the Node.js runtime v4.3. For more information, see
Programming Model (Node.js) (p. 51)
2.
3.
Next Step
Step 2.2: Create the Execution Role (IAM Role) (p. 200)
Java
Use the following Java code to create your Lambda function (AndroidBackendLambdaFunction). The
code receives Android app event data as the first parameter to the handler. Then, the code processes
event data (for illustration this code writes some of the event data to CloudWatch Logs and returns a
string in response).
In the code, the handler (myHandler) uses the RequestClass and ResponseClass types for the
input and output. The code provides implementation for these types.
Important
You use the same classes (POJOs) to handle the input and output data when you create the
sample mobile application in the next section.
package example;
198
import com.amazonaws.services.lambda.runtime.Context;
public class HelloPojo {
// Define two classes/POJOs for use with Lambda function.
public static class RequestClass {
String firstName;
String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public RequestClass(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public RequestClass() {
}
}
public static class ResponseClass {
String greetings;
public String getGreetings() {
return greetings;
}
public void setGreetings(String greetings) {
this.greetings = greetings;
}
public ResponseClass(String greetings) {
this.greetings = greetings;
}
public ResponseClass() {
}
}
public static ResponseClass myHandler(RequestClass request, Context context){
String greetingString = String.format("Hello %s, %s.", request.firstName,
request.lastName);
199
context.getLogger().log(greetingString);
return new ResponseClass(greetingString);
}
}
Save the preceding code in a file (HelloPojo.java). Your can now create a deployment package. You
need to include the following dependency:
aws-lambda-java-core
Your deployment package can be a .zip file or a standalone .jar. You can use any build and packaging
tool you are familiar with to create a deployment package. For examples of how to use the Maven build
tool to create a standalone .jar, see Creating a .jar Deployment Package Using Maven without any IDE
(Java) (p. 91) and Creating a .jar Deployment Package Using Maven and Eclipse IDE (Java) (p. 93). For
an example of how to use the Gradle build tool to create a .zip file, see Creating a .zip Deployment
Package (Java) (p. 96).
After you verify that your deployment package (lambda-java-example-1.0-SNAPSHOT.jar) is created,
go to the next section to create an IAM role (execution role). You specify the role when you create your
Lambda function.
Next Step
Step 2.2: Create the Execution Role (IAM Role) (p. 200)
3.
Write down the role ARN. You will need it in the next step when you create your Lambda function.
200
Next Step
Step 2.3: Create the Lambda Function and Invoke It Manually (Using Sample Event Data) (p. 201)
Step 2.3: Create the Lambda Function and Invoke It Manually (Using Sample
Event Data)
In this section, you do the following:
Create a Lambda function, by uploading the deployment package.
Test the Lambda function by invoking it manually. Instead of creating an event source, you use sample
event data. In the next section, you create an Android mobile app and test the end-to-end experience.
Optionally, you can upload the .zip file to an Amazon S3 bucket in the same AWS region, and then specify
the bucket and object name in the preceding command.You need to replace the --zip-file parameter
by the --code parameter, as shown following:
--code S3Bucket=bucket-name,S3Key=zip-file-object-key
Note
You can create the Lambda function using the AWS Lambda console, in which case note the
value of the create-function AWS CLI command parameters. You provide the same values
in the console UI.
Follow the steps in the Getting Started exercise to create and invoke the Lambda function at Step
2.2: Invoke the Lambda Function Manually and Verify Results, Logs, and Metrics (p. 42). After you
201
choose the Lambda function, choose Configure test event from the Actions menu to specify the
following sample event data:
{
2.
"firstName": "first-name",
"lastName": "last-name" }
2.
"firstName": "first-name",
"lastName": "last-name" }
Note
In this tutorial example, the message is saved in the outputfile.txt file. If you request
synchronous execution (RequestResponse as the invocation type), the function returns
the string message in the response body.
For Node.js, it could be one of the following (whatever one you specify in the code):
context.succeed("message")
context.fail("message")
context.done(null, "message)
For Java, it is the message in the return statement:
return "message"
Next Step
Step 3: Create an Amazon Cognito Identity Pool (p. 203)
202
Using the IAM User Sign-In URL, sign in to the Amazon Cognito console as adminuser.
2.
203
"arn:aws:lambda:us-east-1:account-id:function:AndroidBackend
LambdaFunction"
]
}
]
}
Note
You can update policy at the time of creating the identity pool. You can also update the
policy after you create the identity pool, in which case make sure you write down the IAM
role name for the unauthenticated users from the Amazon Cognito console. Then, go to
the IAM console and search for the specific role and edit the access permissions policy.
For instructions about how to create an identity pool, log in to the Amazon Cognito console and follow
the New Identity Pool wizard.
3.
Note down the identity pool ID. You specify this ID in your mobile application you create in the next
section. The app uses this ID when it sends request to Amazon Cognito to request for temporary
security credentials.
Next Step
Step 4: Create a Mobile Application for Android (p. 204)
Create a new Android project called AndroidEventGenerator using the following configuration:
Select the Phone and Tablet platform.
Choose Blank Activity.
2.
In the build.gradle (Module:app) file, add the following in the dependencies section:
compile 'com.amazonaws:aws-android-sdk-core:2.2.+'
compile 'com.amazonaws:aws-android-sdk-lambda:2.2.+'
3.
4.
Build the project so that the required dependencies are downloaded, as needed.
In the Android application manifest (AndroidManifest.xml), add the following permissions so that
your application can connect to the Internet. You can add them just before the </manifest> end
tag.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
5.
204
import com.amazonaws.mobileconnectors.lambdainvoker.*;
import com.amazonaws.auth.CognitoCachingCredentialsProvider;
import com.amazonaws.regions.Regions;
6.
In the package section, add the following two classes (RequestClass and ResponseClass). Note
that the POJO is same as the POJO you created in your Lambda function in the preceding section.
RequestClass. The instances of this class act as the POJO (Plain Old Java Object) for event
data which consists of first and last name. If you are using Java example for your Lambda function
you created in the preceding section, this POJO is same as the POJO you created in your Lambda
function code.
package com.example....lambdaeventgenerator;
public class RequestClass {
String firstName;
String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public RequestClass(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public RequestClass() {
}
}
ResponseClass
package com.example....lambdaeventgenerator;
public class ResponseClass {
String greetings;
public String getGreetings() {
return greetings;
}
public void setGreetings(String greetings) {
this.greetings = greetings;
}
205
7.
In the same package, create interface called MyInterface for invoking the
AndroidBackendLambdaFunction Lambda function.
Note
The @LambdaFunction annotation in the code maps the specific client method to the
same-name Lambda function. For more information about this annotation, see AWS Lambda
in the AWS Mobile SDK for Android Developer Guide.
package com.example.....lambdaeventgenerator;
import com.amazonaws.mobileconnectors.lambdainvoker.LambdaFunction;
public interface MyInterface {
/**
* Invoke the Lambda function "AndroidBackendLambdaFunction".
* The function name is the method name.
*/
@LambdaFunction
ResponseClass AndroidBackendLambdaFunction(RequestClass request);
}
8.
To keep the application simple, we are going to add code to invoke the Lambda function in the
onCreate() event handler. In MainActivity, add the following code toward the end of the
onCreate() code.
// Create an instance of CognitoCachingCredentialsProvider
CognitoCachingCredentialsProvider cognitoProvider = new CognitoCachingCre
dentialsProvider(
this.getApplicationContext(), "identity-pool-id", Regions.US_WEST_2);
// Create LambdaInvokerFactory, to be used to instantiate the Lambda proxy.
LambdaInvokerFactory factory = new LambdaInvokerFactory(this.getApplication
Context(),
Regions.US_WEST_2, cognitoProvider);
// Create the Lambda proxy object with a default Json data binder.
// You can provide your own data binder by implementing
// LambdaDataBinder.
final MyInterface myInterface = factory.build(MyInterface.class);
RequestClass request = new RequestClass("John", "Doe");
// The Lambda function invocation results in a network call.
// Make sure it is not called from the main thread.
new AsyncTask<RequestClass, Void, ResponseClass>() {
@Override
206
9.
207
Note
Each AWS account can have up to 50 unique event sources of the CloudWatch Events Schedule source type. Each of these can be the event source for up to five Lambda functions.
That is, you can have up to 250 Lambda functions that can be executing on a schedule in your
AWS account.
The console also provides a blueprint (lambda-canary) that uses the CloudWatch Events - Schedule
source type. Using this blueprint, you can create a sample Lambda function and test this feature. The
example code that the blueprint provides checks for the presence of a specific webpage and specific text
string on the webpage. If either the webpage or the text string is not found, the Lambda function throws
an error.
For a tutorial that walks you through an example setup, see Tutorial: Using AWS Lambda with Scheduled
Events (p. 208).
Next Step
Step 1: Create a Lambda Function (p. 208)
Sign in to the AWS Management Console and open the AWS Lambda console at https://
console.aws.amazon.com/lambda/.
Choose Create a Lambda function.
3.
4.
208
Note
When setting a rate expression, the first execution is immediate and subsequent executions
occur based on the rate schedule. In the preceding example, the subsequent execution
rate would be every minute.
For more information on expressions schedules, see Schedule Expressions Using Rate or
Cron (p. 210).
In Enable trigger, we recommend that you leave the trigger in a disabled state until you have
tested it.
5.
6.
Next Step
Step 2: Test the Lambda Function (Using a Sample Test Event) (p. 209)
Choose the function you created in the previous step and then choose Test.
2.
On the Input sample event page, choose Scheduled Event in the Sample event list.
3.
Note the event time in the sample event. This value will be different when AWS Lambda invokes the
function at scheduled intervals. The sample Lambda function code logs this time to CloudWatch
Logs.
Choose Submit and verify that the Execution result section shows success.
Next Step
Step 3: Create an Amazon SNS Topic and Subscribe to It (p. 209)
Create an SNS topic using the Amazon SNS console. For instructions, see Create a Topic in the
Amazon Simple Notification Service Developer Guide.
209
2.
Subscribe to the topic. For this exercise, use email as the communication protocol. For instructions,
see Subscribe to a Topic in the Amazon Simple Notification Service Developer Guide.
You use this Amazon SNS topic in the next step when you configure a CloudWatch alarm so that when
AWS Lambda emits an error the alarm will publish a notification to this topic.
Next Step
Step 4: Configure a CloudWatch Alarm (p. 210)
Next Step
Step 5: Test the Lambda Function Again (p. 210)
Where:
Value can be a positive integer.
Unit can be minute(s), hour(s), or day(s).
For example:
Example
Cron expression
rate(5 minutes)
rate(1 hour)
210
Example
Cron expression
rate(7 days)
Cron expression
cron(Minutes Hours Day-of-month Month Day-of-week Year)
All fields are required and time zone is UTC only. The following table describes these fields.
Field
Values
Wildcards
Minutes
0-59
,-*/
Hours
0-23
,-*/
Day-of-month
1-31
,-*?/LW
Month
1-12 or JAN-DEC
,-*/
Day-of-week
1-7 or SUN-SAT
,-*?/L#
Year
1970-2199
,-*/
Definition
Example
Specifies increments
Specifies "Last"
Specifies Weekday When used with a date, such as 5/W, specifies the closest
weekday to 5th day of the month. If the 5th falls on a Saturday,
execution occurs on Friday. If the 5th falls on a Sunday, execution occurs on Monday.
Specifies the nd or Specifying 3#2 means the second Tuesday of the month
nth day of the
(Tuesday is the third day of the 7-day week).
month
Specifies All values If used in the Day-of-month field, it means all days in the
month.
211
Character
Definition
Example
No specified value Used in conjunction with another specified value. For example,
if a specific date is specified, but you don't care what day of
the week it falls on.
Specifies ranges
Specifies additional SUN, MON, TUE means Sunday, Monday and Tuesday
values
Specifies increments
Cron expression
cron(0 10 * * ? *)
cron(15 12 * * ? *)
cron(0 18 ? * MON-FRI *)
cron(0 8 1 * ? *)
cron(0/10 * ? * MON-FRI *)
212
When a user application invokes a Lambda function, it's an example of the AWS Lambda request-response
model in which an application invokes a Lambda function and receives a response in real time. For more
information, see How It Works (p. 3).
For a tutorial that walks you through an example setup, see Tutorial: Using AWS Lambda with Custom
User Applications (p. 213).
Note
The code sample is compliant with the Node.js runtime v4.3. For more information, see
Programming Model (Node.js) (p. 51)
The function is simple. It processes incoming event data by logging it (these logs are available in
Amazon CloudWatch), and in the request-response model, you can request the log data be returned
in the response.
Simulate a user application that sends an event to your Lambda function by invoking your Lambda
function manually using the following sample event data.
{
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
Note
This example is similar to the Getting Started exercise (see Getting Started (p. 35)).The difference
is that the Getting Started exercise provides a console-based experience. The console does
many things for you, which simplifies the experience. When using the AWS CLI, you get the
experience of making the API calls, which can help you develop a better understanding of the
AWS Lambda operations. In addition to creating and invoking a Lambda function, you can explore
other Lambda APIs.
213
Next Step
Step 1: Prepare (p. 214)
Step 1: Prepare
Make sure you have completed the following steps:
Signed up for an AWS account and created an administrator user in the account.
Installed and set up the AWS CLI.
For instructions, see Step 1: Set Up an AWS Account and the AWS CLI (p. 35).
Next Step
Step 2: Create a Lambda Function and Invoke It Manually (p. 214)
214
};
Note
The code sample is compliant with the Node.js runtime v4.3. For more information, see
Programming Model (Node.js) (p. 51)
2.
3.
Note
To see more examples of using other AWS services within your function, including calling other
Lambda functions, see AWS SDK for JavaScript
2.
Follow the steps in Creating a Role to Delegate Permissions to an AWS Service in the IAM User
Guide to create an IAM role (execution role). As you follow the steps to create a role, note the
following:
In Role Name, use a name that is unique within your AWS account (for example,
lambda-custom-app-execution-role).
In Select Role Type, choose AWS Service Roles, and then choose AWS Lambda. This grants
the AWS Lambda service permissions to assume the role.
In Attach Policy, choose AWSLambdaBasicExecutionRole.
3.
Write down the role ARN. You will need it in the next step when you create your Lambda function.
215
Optionally, you can upload the .zip file to an Amazon S3 bucket in the same AWS region, and then specify
the bucket and object name in the preceding command.You need to replace the --zip-file parameter
by the --code parameter, as shown following:
--code S3Bucket=bucket-name,S3Key=zip-file-object-key
For more information, see CreateFunction (p. 283). AWS Lambda creates the function and returns function
configuration information as shown in the following example:
{
"FunctionName": "helloworld",
"CodeSize": 351,
"MemorySize": 128,
"FunctionArn": "function-arn",
"Handler": "helloworld.handler",
"Role": "arn:aws:iam::account-id:role/LambdaExecRole",
"Timeout": 3,
"LastModified": "2015-04-07T22:02:58.854+0000",
"Runtime": "nodejs4.3",
"Description": ""
}
Next Step
Step 3: Invoke the Lambda Function (AWS CLI) (p. 216)
216
If you want you can save the payload to a file (for example, input.txt) and provide the file name as a
parameter.
--payload file://input.txt \
The preceding invoke command specifies RequestResponse as the invocation type, which returns a
response immediately in response to the function execution. Alternatively, you can specify Event as the
invocation type to invoke the function asynchronously.
By specifying the --log-type parameter, the command also requests the tail end of the log produced
by the function. The log data in the response is base64-encoded as shown in the following example
response:
{
"LogResult": "base64-encoded-log",
"StatusCode": 200
}
On Linux and Mac, you can use the base64 command to decode the log.
$ echo base64-encoded-log | base64 --decode
Note
You are able to execute this function because you are using the same AWS account to create
and invoke the Lambda function. However, if you want to grant cross-account permissions to
another AWS account or grant permissions to another an AWS service to execute the function,
you must add a permissions to the access permissions policy associated with the function. The
Amazon S3 tutorial, which uses Amazon S3 as the event source (see Tutorial: Using AWS
Lambda with Amazon S3 (p. 127)), grants such permissions to Amazon S3 to invoke the function.
217
You can monitor the activity of your Lambda function in the AWS Lambda console.
Sign in to the AWS Management Console and open the AWS Lambda console at https://
console.aws.amazon.com/lambda/.
The AWS Lambda console shows a graphical representation of some of the CloudWatch metrics in
the Cloudwatch Metrics at a glance section for your function.
For each graph, you can also choose the logs link to view the CloudWatch logs directly.
Next Step
Step 4: Try More CLI Commands (AWS CLI) (p. 218)
To illustrate the use of pagination, the command specifies the optional --max-items parameter to limit
the number of functions returned in the response. For more information, see ListFunctions (p. 314). The
following is an example response.
{
"Functions": [
{
"FunctionName": "helloworld",
"MemorySize": 128,
"CodeSize": 412,
"FunctionArn": "arn:aws:lambda:us-east-1:account-id:function:Pro
cessKinesisRecords",
"Handler": "ProcessKinesisRecords.handler",
"Role": "arn:aws:iam::account-id:role/LambdaExecRole",
"Timeout": 3,
"LastModified": "2015-02-22T21:03:01.172+0000",
"Runtime": "nodejs4.3",
"Description": ""
},
{
"FunctionName": "ProcessKinesisRecords",
"MemorySize": 128,
"CodeSize": 412,
"FunctionArn": "arn:aws:lambda:us-east-1:account-id:function:Pro
cessKinesisRecords",
"Handler": "ProcessKinesisRecords.handler",
"Role": "arn:aws:iam::account-id:role/lambda-execute-test-kinesis",
"Timeout": 3,
"LastModified": "2015-02-22T21:03:01.172+0000",
"Runtime": "nodejs4.3",
218
"Description": ""
},
...
],
"NextMarker": null
}
In response, Lambda returns a list of up to 10 functions. If there are more functions you can retrieve,
NextMarker provides a marker you can use in the next list-functions request; otherwise, the value
is null.The following list-functions AWS CLI command is an example that shows the --next-marker
parameter.
$ aws lambda list-functions \
--max-items 10 \
--marker value-of-NextMarker-from-previous-response \
--profile adminuser
Step 4.2: Get Metadata and a URL to Download Previously Uploaded Lambda
Function Deployment Packages
The Lambda CLI get-function command returns Lambda function metadata and a presigned URL
that you can use to download the function's .zip file (deployment package) that you uploaded to create
the function. For more information, see GetFunction (p. 297).
$ aws lambda get-function \
--function-name helloworld \
--region us-west-2 \
--profile adminuser
219
If you want the function configuration information only (not the presigned URL), you can use the Lambda
CLI get-function-configuration command.
$ aws lambda get-function-configuration \
--function-name helloworld \
--region us-west-2 \
--profile adminuser
Next Step
Step 5: Delete the Lambda Function and IAM Role (AWS CLI) (p. 220)
Step 5: Delete the Lambda Function and IAM Role (AWS CLI)
Execute the following delete-function command to delete the helloworld function.
$ aws lambda delete-function \
--function-name helloworld \
--region us-west-2 \
--profile adminuser
220
Important
AWS Lambda does not support connecting to resources within Dedicated Tenancy VPCs. For
more information, see Dedicated VPCs.
221
--runtime python2.7 \
--role execution-role-arn \
--zip-file fileb://path/app.zip \
--handler app.handler \
--vpc-config SubnetIds=comma-separated-vpc-subnet-ids,SecurityGroupIds=commaseparated-security-group-ids \
--memory-size 1024 \
--profile adminuser
Note
The Lambda function execution role must have permissions to create ENIs. AWS Lambda
provides a permissions policy, AWSLambdaVPCAccessExecutionRole, with permissions for
the necessary EC2 actions (ec2:CreateNetworkInterface,
ec2:DescribeNetworkInterfaces, and ec2:DeleteNetworkInterface) that you can
use when creating a role. You can review the policy in the IAM console.
The update-function-configuration CLI command specifies the --vpc-config parameter to
add VPC information to an existing Lambda function configuration.
$ aws lambda update-function-configuration \
--function-name ExampleFunction \
--vpc-config SubnetIds=comma-separated-vpc-subnet-ids,SecurityGroupIds=secur
ity-group-ids
To remove VPC-related information from your Lambda function configuration, use the
UpdateFunctionConfiguration API by providing an empty list of subnet IDs and security group
IDs as shown in the following example CLI command.
$ aws lambda update-function-configuration \
--function-name ExampleFunction \
--vpc-config SubnetIds=[],SecurityGroupIds=[]
When you add VPC configuration to a Lambda function, it can only access resources in that VPC. If a
Lambda function needs to access both VPC resources and the public Internet, the VPC needs to have
a Network Address Translation (NAT) instance inside the VPC.
When a Lambda function is configured to run within a VPC, it incurs an additional ENI start-up penalty.
This means address resolution may be delayed when trying to connect to network resources.
222
Subnets you specify, but is not assigned any public IP addresses. Therefore, if your Lambda function
requires Internet access (for example, to access AWS services that don't have VPC endpoints, such as
Amazon Kinesis), you can configure a NAT instance inside your VPC or you can use the Amazon VPC
NAT gateway. For more information, see NAT Gateways in the Amazon VPC User Guide. You cannot
use an Internet gateway attached to your VPC, since that requires the ENI to have public IP addresses.
Important
If your Lambda function needs Internet access, do not attach it to a public subnet or to a private
subnet without Internet access. Instead, attach it only to private subnets with Internet access
through a NAT instance or an Amazon VPC NAT gateway.
Where:
Projected peak concurrent execution Use the information in Lambda Function Concurrent
Executions (p. 28) to determine this value.
Memory The amount of memory you configured for your Lambda function.
The subnets you specify should have sufficient available IP addresses to match the number of ENIs.
We also recommend that you specify at least one subnet in each Availability Zone in your Lambda
function configuration. By specifying subnets in each of the Availability Zones, your Lambda function
can run in another Availability Zone if one goes down or runs out of IP addresses.
Caution
If your VPC does not have sufficient ENIs or subnet IPs, your Lambda function will not scale as
requests increase, and you will see an increase in function failures. AWS Lambda currently does
not log errors to CloudWatch Logs that are caused by insufficient ENIs or IP addresses. If you
see an increase in errors without corresponding CloudWatch Logs, you can invoke the Lambda
function synchronously to get the error responses (for example, test your Lambda function in
the AWS Lambda console because the console invokes your Lambda function synchronously
and displays errors).
Topics
Tutorials: Accessing Resources in an Amazon VPC (p. 224)
223
Important
This tutorial uses the default Amazon VPC in the us-east-1 region in your account. For more
information about Amazon VPC, see How to Get Started with Amazon VPC in the Amazon VPC
User Guide.
Next Step
Step 1: Create an ElastiCache Cluster (p. 224)
Run the following AWS CLI command to create a Memcached cluster in the default VPC in the
us-east-1 region in your account.
aws elasticache create-cache-cluster \
--cache-cluster-id ClusterForLambdaTest \
--cache-node-type cache.m3.medium \
--engine memcached \
--security-group-ids your-default-vpc-security-group \
--num-cache-nodes 1
You can look up the default VPC security group in the VPC console under Security Groups. Your
example Lambda function will add and retrieve an item from this cluster.
224
2.
You can also launch a cache cluster using the Amazon ElastiCache console. For instructions, see
Getting Started with Amazon ElastiCache in the Amazon ElastiCache User Guide.
Write down the configuration endpoint for the cache cluster that you launched. You can get this from
the Amazon ElastiCache console. You will specify this value in your Lambda function code in the
next section.
Next Step
Step 2: Create a Lambda Function (p. 225)
Python
The following example Python code reads and writes an item to your ElastiCache cluster.
1.
225
2.
3.
4.
Zip all of these files into a file named app.zip to create your deployment package. For step-by-step
instructions, see Creating a Deployment Package (Python) (p. 98).
Next Step
Step 2.2: Create the Execution Role (IAM Role) (p. 226)
226
2.
Follow the steps in Creating a Role to Delegate Permissions to an AWS Service in the IAM User
Guide to create an IAM role (execution role). As you follow the steps to create a role, note the
following:
In Role Name, use a name that is unique within your AWS account (for example,
lambda-vpc-execution-role).
In Select Role Type, choose AWS Service Roles, and then choose AWS Lambda. This grants
the AWS Lambda service permissions to assume the role.
In Attach Policy, choose AWSLambdaVPCAccessExecutionRole.The permissions in this policy
are sufficient for the Lambda function in this tutorial.
3.
Write down the role ARN. You will need it in the next step when you create your Lambda function.
Next Step
Step 2.3: Create the Lambda Function (Upload the Deployment Package) (p. 227)
Step 2.3: Create the Lambda Function (Upload the Deployment Package)
In this step, you create the Lambda function (AccessMemCache) using the create-function AWS CLI
command.
At the command prompt, run the following Lambda CLI create-function command using the adminuser
profile.
You need to update the following create-function command by providing the .zip file path and the
execution role ARN.The --runtime parameter value can be python2.7, nodejs and java8, depending
on the language you used to author your code.
Note
At this time, example code for the Lambda function is provided only in Python.
$ aws lambda create-function \
--function-name AccessMemCache \
--region us-east-1 \
--zip-file fileb://path-to/app.zip \
--role execution-role-arn \
--handler app.handler \
--runtime python2.7 \
--timeout 30 \
--vpc-config SubnetIds=comma-separated-vpc-subnet-ids,SecurityGroupIds=defaultsecurity-group-id \
--memory-size 1024 \
--profile adminuser
You can find the subnet IDs and the default security group ID of your VPC from the VPC console.
Optionally, you can upload the .zip file to an Amazon S3 bucket in the same AWS region, and then specify
the bucket and object name in the preceding command.You need to replace the --zip-file parameter
by the --code parameter, as shown following:
--code S3Bucket=bucket-name,S3Key=zip-file-object-key
227
Note
You can also create the Lambda function using the AWS Lambda console. When creating the
function, choose a VPC for the Lambda and then select the subnets and security groups from
the provided fields.
Next Step
Step 3: Test the Lambda Function (Invoke Manually) (p. 228)
Invoke the Lambda function (AccessMemCache) using the AWS Lambda invoke command.
$ aws lambda invoke \
--function-name AccessMemCache
--region us-east-1 \
--profile adminuser \
output.txt
2.
What Next?
Now that you have created a Lambda function that accesses an ElastiCache cluster in your VPC, you
can have the function invoked in response to events. For information about configuring event sources
and examples, see Use Cases (p. 125).
Important
This tutorial uses the default Amazon VPC in the us-east-1 region in your account. For more
information about Amazon VPC, see How to Get Started with Amazon VPC in the Amazon VPC
User Guide.
228
Next Step
Step 1: Create an Amazon RDS MySQL Instance and ExampleDB Database (p. 229)
Where EmpID is the primary key. Now, you need to add a few records to this table.
First, you launch an RDS MySQL instance in your default VPC with ExampleDB database. If you already
have an RDS MySQL instance running in your default VPC, skip this step.
Important
This tutorial uses the RDS MySQL DB engine launched in the default VPC in the us-east-1
region.
You can launch an RDS MySQL instance using one of the following methods:
Follow the instructions at Creating a MySQL DB Instance and Connecting to a Database on a MySQL
DB Instance in the Amazon Relational Database Service User Guide.
Use the following AWS CLI command:
$ aws rds create-db-instance \
--db-instance-identifier MySQLForLambdaTest \
--db-instance-class db.t2.micro \
--engine MySQL \
--allocated-storage 5 \
--no-publicly-accessible \
--db-name ExampleDB \
--master-username username \
--master-user-password password \
--backup-retention-period 3 \
--profile adminuser
Write down the database name, user name, and password. You also need the host address (endpoint)
of the DB instance, which you can get from the RDS console (you might need to wait until the instance
status is available and the Endpoint value appears in the console).
Next Step
Step 2: Create a Lambda Function (p. 229)
229
The permissions policy associated with this role grants AWS Lambda permissions to set up elastic
network interfaces (ENIs) to enable your Lambda function to access resources in the VPC.
Create the Lambda function by uploading the deployment package.
Topics
Step 2.1: Create a Deployment Package (p. 230)
Step 2.2: Create the Execution Role (IAM Role) (p. 231)
Step 2.3: Create the Lambda Function (Upload the Deployment Package) (p. 232)
Python
The following example Python code runs a SELECT query against the Employee table in the MySQL
RDS instance that you created in the VPC. The code creates a table in the ExampleDB database, adds
sample records, and retrieves those records.
1.
logger = logging.getLogger()
logger.setLevel(logging.INFO)
try:
conn = pymysql.connect(rds_host, user=name, passwd=password, db=db_name,
connect_timeout=5)
except:
logger.error("ERROR: Unexpected error: Could not connect to MySql in
stance.")
sys.exit()
logger.info("SUCCESS: Connection to RDS mysql instance succeeded")
def handler(event, context):
"""
This function fetches content from mysql RDS instance
"""
item_count = 0
with conn.cursor() as cur:
cur.execute("create table Employee3 ( EmpID int NOT NULL, Name
varchar(255) NOT NULL, PRIMARY KEY (EmpID))")
cur.execute('insert into Employee3 (EmpID, Name) values(1, "Joe")')
230
Note
We recommend that pymysql.connect() is executed outside the handler, as shown, for
better performance.
2.
3.
4.
Create a config file that contains the following information and save it as rds_config.py:
#config file containing credentials for rds mysql instance
db_username = "username"
db_password = "password"
db_name = "databasename"
5.
Zip all of these files into a file named app.zip to create your deployment package. For step-by-step
instructions, see Creating a Deployment Package (Python) (p. 98).
Next Step
Step 2.2: Create the Execution Role (IAM Role) (p. 231)
231
2.
Follow the steps in Creating a Role to Delegate Permissions to an AWS Service in the IAM User
Guide to create an IAM role (execution role). As you follow the steps to create a role, note the
following:
In Role Name, use a name that is unique within your AWS account (for example,
lambda-vpc-execution-role).
In Select Role Type, choose AWS Service Roles, and then choose AWS Lambda. This grants
the AWS Lambda service permissions to assume the role.
In Attach Policy, choose AWSLambdaVPCAccessExecutionRole.The permissions in this policy
are sufficient for the Lambda function in this tutorial.
3.
Write down the role ARN. You will need it in the next step when you create your Lambda function.
Next Step
Step 2.3: Create the Lambda Function (Upload the Deployment Package) (p. 232)
Step 2.3: Create the Lambda Function (Upload the Deployment Package)
In this step, you create the Lambda function (ReadMySqlTable) using the create-function AWS CLI
command.
At the command prompt, run the following Lambda CLI create-function command using the adminuser
profile.
You need to update the following create-function command by providing the .zip file path and the
execution role ARN.The --runtime parameter value can be python2.7, nodejs, or java8, depending
on the language you used to author your code.
Note
At this time, example code for the Lambda function is provided only in Python.
$ aws lambda create-function \
--region us-east-1 \
--function-name
CreateTableAddRecordsAndRead \
--zip-file fileb://file-path/app.zip \
--role execution-role-arn \
--handler app.handler \
--runtime python2.7 \
--vpc-config SubnetIds=comma-separated-subnet-ids,SecurityGroupIds=default-vpcsecurity-group-id \
--profile adminuser
Optionally, you can upload the .zip file to an Amazon S3 bucket in the same AWS region, and then specify
the bucket and object name in the preceding command.You need to replace the --zip-file parameter
by the --code parameter, as shown following:
--code S3Bucket=bucket-name,S3Key=zip-file-object-key
232
Note
You can also create the Lambda function using the AWS Lambda console (use the parameter
values shown in the preceding CLI command).
Next Step
Step 3: Test the Lambda Function (Invoke Manually) (p. 233)
Invoke the Lambda function (ReadMySqlTable) using the AWS Lambda invoke command.
$ aws lambda invoke \
--function-name CreateTableAddRecordsAndRead
--region us-east-1 \
--profile adminuser \
output.txt
2.
233
234
235
"requestID": "7aebcd0f-cda1-11e4-aaa2-e356da31e4ff",
"eventID": "e92a3e85-8ecd-4d23-8074-843aabfe89bf",
"eventType": "AwsApiCall",
"recipientAccountId": "999999999999"
},
{
"eventVersion": "1.03",
"userIdentity": {
"type": "IAMUser",
"principalId": "A1B2C3D4E5F6G7EXAMPLE",
"arn": "arn:aws:iam::999999999999:user/myUserName",
"accountId": "999999999999",
"accessKeyId": "AKIAIOSFODNN7EXAMPLE",
"userName": "myUserName"
},
"eventTime": "2015-03-18T19:04:42Z",
"eventSource": "lambda.amazonaws.com",
"eventName": "DeleteFunction",
"awsRegion": "us-east-1",
"sourceIPAddress": "127.0.0.1",
"userAgent": "Python-httplib2/0.8 (gzip)",
"requestParameters": {
"functionName": "basic-node-task"
},
"responseElements": null,
"requestID": "a2198ecc-cda1-11e4-aaa2-e356da31e4ff",
"eventID": "20b84ce5-730f-482e-b2b2-e8fcc87ceb22",
"eventType": "AwsApiCall",
"recipientAccountId": "999999999999"
}
]
}
Note
The eventName may include date and version information, such as "GetFunction20150331",
but it is still referring to the same public API.
236
237
Default Limit
512 MB
1,024
1,024
300 seconds
128 K
6 MB
The following table lists the Lambda account limits per region.
238
Default Limit
100
Open the AWS Support Center page, sign in, if necessary, and then click Create case.
Under Regarding, select Service Limit Increase.
3.
Under Limit Type, select Lambda, fill in the necessary fields in the form, and then click the button
at the bottom of the page for your preferred method of contact.
Note
AWS may automatically raise the concurrent execution limit on your behalf to enable your function
to match the incoming event rate, as in the case of triggering the function from an Amazon S3
bucket.
The following table lists service limits for deploying a Lambda function.
Default Limit
50 MB
Total size of all the deployment packages that can be uploaded per region
75 GB
239
Authentication
You can access AWS as any of the following types of identities:
AWS account root user When you sign up for AWS, you provide an email address and password
that is associated with your AWS account. These are your root credentials and they provide complete
access to all of your AWS resources.
Important
For security reasons, we recommend that you use the root credentials only to create an
administrator user, which is an IAM user with full permissions to your AWS account. Then,
you can use this administrator user to create other IAM users and roles with limited permissions.
For more information, see IAM Best Practices and Creating an Admin User and Group in the
IAM User Guide.
IAM user An IAM user is simply an identity within your AWS account that has specific custom
permissions (for example, permissions to create a function in Lambda).You can use an IAM user name
and password to sign in to secure AWS webpages like the AWS Management Console, AWS Discussion
Forums, or the AWS Support Center.
In addition to a user name and password, you can also generate access keys for each user. You can
use these keys when you access AWS services programmatically, either through one of the several
SDKs or by using the AWS Command Line Interface (CLI). The SDK and CLI tools use the access
keys to cryptographically sign your request. If you dont use the AWS tools, you must sign the request
yourself. Lambda supports Signature Version 4, a protocol for authenticating inbound API requests.
240
For more information about authenticating requests, see Signature Version 4 Signing Process in the
AWS General Reference.
IAM role An IAM role is another IAM identity you can create in your account that has specific
permissions. It is similar to an IAM user, but it is not associated with a specific person. An IAM role
enables you to obtain temporary access keys that can be used to access AWS services and resources.
IAM roles with temporary credentials are useful in the following situations:
Federated user access Instead of creating an IAM user, you can use preexisting user identities
from AWS Directory Service, your enterprise user directory, or a web identity provider. These are
known as federated users. AWS assigns a role to a federated user when access is requested through
an identity provider. For more information about federated users, see Federated Users and Roles in
the IAM User Guide.
Cross-account access You can use an IAM role in your account to grant another AWS account
permissions to access your accounts resources. For an example, see Tutorial: Delegate Access
Across AWS Accounts Using IAM Roles in the IAM User Guide.
AWS service access You can use an IAM role in your account to grant an AWS service permissions
to access your accounts resources. For example, you can create a role that allows Amazon Redshift
to access an Amazon S3 bucket on your behalf and then load data stored in the bucket into an
Amazon Redshift cluster. For more information, see Creating a Role to Delegate Permissions to an
AWS Service in the IAM User Guide.
Applications running on Amazon EC2 Instead of storing access keys within the EC2 instance
for use by applications running on the instance and making AWS API requests, you can use an IAM
role to manage temporary credentials for these applications. To assign an AWS role to an EC2
instance and make it available to all of its applications, you can create an instance profile that is
attached to the instance. An instance profile contains the role and enables programs running on the
EC2 instance to get temporary credentials. For more information, see Using Roles for Applications
on Amazon EC2 in the IAM User Guide.
Access Control
You can have valid credentials to authenticate your requests, but unless you have permissions you cannot
create or access AWS Lambda resources. For example, you must have permissions to create a Lambda
function, add an event source, and publish a version of your Lambda function.
The following sections describe how to manage permissions for AWS Lambda. We recommend that you
read the overview first.
Overview of Managing Access Permissions to Your AWS Lambda Resources (p. 242)
Using Identity-Based Policies (IAM Policies) for AWS Lambda (p. 246)
Using Resource-Based Policies for AWS Lambda (Lambda Function Policies) (p. 259)
241
Note
An account administrator (or administrator user) is a user with administrator privileges. For more
information, see IAM Best Practices in the IAM User Guide.
When granting permissions, you decide who is getting the permissions, the resources they get permissions
for, and the specific actions that you want to allow on those resources.
Topics
AWS Lambda Resources and Operations (p. 242)
Understanding Resource Ownership (p. 243)
Managing Access to Resources (p. 243)
Specifying Policy Elements: Actions, Effects, Resources, and Principals (p. 245)
Specifying Conditions in a Policy (p. 246)
ARN Format
Function
arn:aws:lambda:region:account-id:function:function-name
Function alias
arn:aws:lambda:region:account-id:function:function-name:aliasname
Function version
arn:aws:lambda:region:account-id:function:function-name:version
arn:aws:lambda:region:account-id:event-source-mappings:eventsource-mapping-id
AWS Lambda provides a set of operations to work with the Lambda resources. For a list of available
operations, see Actions (p. 271).
242
Note
This section discusses using IAM in the context of AWS Lambda. It doesn't provide detailed
information about the IAM service. For complete IAM documentation, see What Is IAM? in the
IAM User Guide. For information about IAM policy syntax and descriptions, see AWS IAM Policy
Reference in the IAM User Guide.
Policies attached to an IAM identity are referred to as identity-based policies (IAM polices) and policies
attached to a resource are referred to as resource-based policies. AWS Lambda supports both
identity-based (IAM policies) and resource-based policies.
Topics
Identity-Based Policies (IAM Policies) (p. 243)
Resource-Based Policies (Lambda Function Policies) (p. 244)
243
For more information about using IAM to delegate permissions, see Access Management in the IAM
User Guide.
The following is an example policy that grants permissions for the lambda:ListFunctions action on
all resources. In the current implementation, Lambda doesn't support identifying specific resources using
the resource ARNs (also referred to as resource-level permissions) for some of the API actions, so you
must specify a wildcard character (*).
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ListExistingFunctions",
"Effect": "Allow",
"Action": [
"lambda:ListFunctions"
],
"Resource": "*"
}
]
}
For more information about using identity-based policies with Lambda, see Using Identity-Based Policies
(IAM Policies) for AWS Lambda (p. 246). For more information about users, groups, roles, and permissions,
see Identities (Users, Groups, and Roles) in the IAM User Guide.
Important
Lambda function policies are primarily used when you are setting up an event source in AWS
Lambda to grant a service or an event source permissions to invoke your Lambda function (see
Invoke (p. 304)). An exception to this is when an event source (for example, Amazon DynamoDB
or Amazon Kinesis) uses the pull model, where permissions are managed in the Lambda function
execution role instead. For more information, see Event Source Mapping (p. 10).
The following is an example Lambda function policy that has one statement. The statement allows the
Amazon S3 service principal permission for the lambda:InvokeFunction action on a Lambda function
called HelloWorld. The condition ensures that the bucket where the event occurred is owned by the same
account that owns the Lambda function.
{
"Policy":{
"Version":"2012-10-17",
"Statement":[
{
"Effect":"Allow",
"Principal":{
"Service":"s3.amazonaws.com"
244
For more information about using resource-based policies with Lambda, see Using Resource-Based
Policies for AWS Lambda (Lambda Function Policies) (p. 259). For additional information about using IAM
roles (identity-based policies) as opposed to resource-based policies, see How IAM Roles Differ from
Resource-based Policies in the IAM User Guide.
245
Important
We recommend that you first review the introductory topics that explain the basic concepts and
options available for you to manage access to your AWS Lambda resources. For more information,
see Overview of Managing Access Permissions to Your AWS Lambda Resources (p. 242).
The sections in this topic cover the following:
Permissions Required to Use the AWS Lambda Console (p. 247)
AWS Managed (Predefined) Policies for AWS Lambda (p. 247)
Customer Managed Policy Examples (p. 248)
The following shows an example of a permissions policy.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "CreateFunctionPermissions",
"Effect": "Allow",
"Action": [
"lambda:CreateFunction"
],
"Resource": "*"
},
{
"Sid": "PermissionToPassAnyRole",
"Effect": "Allow",
"Action": [
"iam:PassRole"
],
"Resource": "arn:aws:iam::account-id:role/*"
}
]
}
246
The first statement grants permissions for the AWS Lambda action (lambda:CreateFunction) on
a resource by using the Amazon Resource Name (ARN) for the Lambda function. Currently, AWS
Lambda doesn't support permissions for this particular action at the resource-level. Therefore, the
policy specifies a wildcard character (*) as the Resource value.
The second statement grants permissions for the IAM action (iam:PassRole) on IAM roles. The
wildcard character (*) at the end of the Resource value means that the statement allows permission
for the iam:PassRole action on any IAM role. To limit this permission to a specific role, replace the
wildcard character (*) in the resource ARN with the specific role name.
The policy doesn't specify the Principal element because in an identity-based policy you don't specify
the principal who gets the permission. When you attach policy to a user, the user is the implicit principal.
When you attach a permission policy to an IAM role, the principal identified in the role's trust policy gets
the permissions.
For a table showing all of the AWS Lambda API actions and the resources that they apply to, see Lambda
API Permissions: Actions, Resources, and Conditions Reference (p. 263).
Note
You can review these permissions policies by signing in to the IAM console and searching for
specific policies there.
In addition, there are other AWS-managed policies that are suitable for use with IAM role (execution role)
you specify at the time of creating a Lambda function. For more information, see AWS Lambda Permissions
Model (p. 31).
247
You can also create your own custom IAM policies to allow permissions for AWS Lambda API actions
and resources. You can attach these custom policies to the IAM users or groups that require those
permissions or to custom execution roles (IAM roles) that you create for your Lambda functions.
248
]
}
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "DisplayFunctionDetailsPermissions",
"Effect": "Allow",
"Action": [
"lambda:ListVersionsByFunction",
"lambda:ListAliases",
"lambda:GetFunction",
"lambda:GetFunctionConfiguration",
"lambda:ListEventSourceMappings",
"lambda:GetPolicy"
],
"Resource": "*"
}
]
}
249
To enable the user to see the Lambda function's CloudWatch metrics on the console's Monitoring tab,
or on the grid view on the console home page, you must grant the following permissions:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "CloudWatchPermission",
"Effect": "Allow",
"Action": [
"cloudwatch:GetMetricStatistics"
],
"Resource": "*"
}
]
}
To enable a user to click the links to CloudWatch Logs in the AWS Lambda console and view log output
in CloudWatch Logs, you must grant the following permissions:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "CloudWatchLogsPerms",
"Effect": "Allow",
"Action": [
"cloudwatchlog:DescribeLogGroups",
"cloudwatchlog:DescribeLogStreams",
"cloudwatchlog:GetLogEvents"
],
"Resource": "arn:aws:logs:region:account-id:log-group:/aws/lambda/*"
}
]
}
250
},
{
"Sid": "CreateFunctionPermissions",
"Effect": "Allow",
"Action": [
"lambda:CreateFunction"
],
"Resource": "*"
},
{
"Sid": "PermissionToPassAnyRole",
"Effect": "Allow",
"Action": [
"iam:PassRole"
],
"Resource": "arn:aws:iam::account-id:role/*"
}
]
}
If you want a user to be able to create an IAM role when the user is creating a Lambda function, the user
needs permissions to perform the iam:PutRolePolicy action, as shown following:
{
"Sid": "CreateARole",
"Effect": "Allow",
"Action": [
"iam:PutRolePolicy"
],
"Resource": "arn:aws:iam::account-id:role/*"
}
Important
Each IAM role has a permissions policy attached to it, which grants specific permissions to the
role. Regardless of whether the user creates a new role or uses an existing role, the user must
have permissions for all of the actions granted in the permissions policy associated with the role.
You must grant the user additional permissions accordingly.
251
If you are new to managing permissions, we recommend that you start with the example walkthrough
where you create an IAM user, grant the user incremental permissions, and verify the permissions work
using the AWS Lambda console (see Customer Managed Policy Examples (p. 248)).
Topics
Amazon API Gateway (p. 252)
Amazon CloudWatch Events (p. 253)
Amazon CloudWatch Logs (p. 253)
Amazon Cognito (p. 254)
Amazon DynamoDB (p. 255)
Amazon Kinesis Streams (p. 256)
Amazon S3 (p. 257)
Amazon SNS (p. 258)
AWS IoT (p. 258)
Note
All of these permissions policies grant the specific AWS services permissions to invoke a Lambda
function.The user who is configuring this integration must have permissions to invoke the Lambda
function. Otherwise, the user can't set the configuration. You can attach the AWSLambdaRole
AWS managed (predefined) permissions policy to the user to provide these permissions.
252
}
]
}
253
"Action": [
"logs:FilterLogEvents",
"logs:DescribeLogGroups",
"logs:PutSubscriptionFilter",
"logs:DescribeSubscriptionFilters",
"logs:DeleteSubscriptionFilter",
"logs:TestMetricFilter"
],
"Resource": "arn:aws:logs:region:account-id:*"
},
{
"Sid": "AddPermissionToFunctionPolicy",
"Effect": "Allow",
"Action": [
"lambda:AddPermission",
"lambda:RemovePermission",
"lambda:GetPolicy"
],
"Resource": "arn:aws:lambda:region:account-id:function:*"
},
{
"Sid": "ListEventSourceMappingsPerms",
"Effect": "Allow",
"Action": [
"lambda:ListEventSourceMappings"
],
"Resource": "*"
}
]
}
Note
The additional permissions shown are required for managing subscription filters.
Amazon Cognito
The console lists identity pools in your account. After you select a pool, you can configure the pool to
have the Cognito sync trigger as the event source type. To do this, you need to grant the following
additional permissions:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "CognitoPerms1",
"Effect": "Allow",
"Action": [
"cognito-identity:ListIdentityPools"
],
"Resource": [
"arn:aws:cognito-identity:region:account-id:*"
]
},
{
"Sid": "CognitoPerms2",
"Effect": "Allow",
254
"Action": [
"cognito-sync:GetCognitoEvents",
"cognito-sync:SetCognitoEvents"
],
"Resource": [
"arn:aws:cognito-sync:region:account-id:*"
]
},
{
"Sid": "AddPermissionToFunctionPolicy",
"Effect": "Allow",
"Action": [
"lambda:AddPermission",
"lambda:RemovePermission",
"lambda:GetPolicy"
],
"Resource": "arn:aws:lambda:region:account-id:function:*"
},
{
"Sid": "ListEventSourcePerms",
"Effect": "Allow",
"Action": [
"lambda:ListEventSourceMappings"
],
"Resource": "*"
}
]
}
Amazon DynamoDB
The console lists all of the tables in your account. After you select a table, the console checks to see if a
DynamoDB stream exists for that table. If not, it creates the stream. If you want the user to be able to
configure a DynamoDB stream as an event source for a Lambda function, you need to grant the following
additional permissions:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "DDBpermissions1",
"Effect": "Allow",
"Action": [
"dynamodb:DescribeStream",
"dynamodb:DescribeTable",
"dynamodb:UpdateTable"
],
"Resource": "arn:aws:dynamodb:region:account-id:table/*"
},
{
"Sid": "DDBpermissions2",
"Effect": "Allow",
"Action": [
"dynamodb:ListStreams",
"dynamodb:ListTables"
],
255
"Resource": "*"
},
{
"Sid": "LambdaGetPolicyPerm",
"Effect": "Allow",
"Action": [
"lambda:GetPolicy"
],
"Resource": "arn:aws:lambda:region:account-id:function:*"
},
{
"Sid": "LambdaEventSourcePerms",
"Effect": "Allow",
"Action": [
"lambda:CreateEventSourceMapping",
"lambda:DeleteEventSourceMapping",
"lambda:GetEventSourceMapping",
"lambda:ListEventSourceMappings",
"lambda:UpdateEventSourceMapping"
],
"Resource": "*"
}
]
}
Important
For a Lambda function to read from a DynamoDB stream, the execution role associated with
the Lambda function must have the correct permissions. Therefore, the user must also have the
same permissions before you can grant the permissions to the execution role. You can grant
these permissions by attaching the AWSLambdaDynamoDBExecutionRole predefined policy,
first to the user and then to the execution role.
256
},
{
"Sid": "PermissionForGetFunctionPolicy",
"Effect": "Allow",
"Action": [
"lambda:GetPolicy"
],
"Resource": "arn:aws:lambda:region:account-id:function:*"
},
{
"Sid": "LambdaEventSourcePerms",
"Effect": "Allow",
"Action": [
"lambda:CreateEventSourceMapping",
"lambda:DeleteEventSourceMapping",
"lambda:GetEventSourceMapping",
"lambda:ListEventSourceMappings",
"lambda:UpdateEventSourceMapping"
],
"Resource": "*"
}
]
}
Amazon S3
The console prepopulates the list of buckets in the AWS account and finds the bucket location for each
bucket. When you configure Amazon S3 as an event source, the console updates the bucket notification
configuration. For this to work, you need to grant the following additional permissions:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "S3Permissions",
"Effect": "Allow",
"Action": [
"s3:GetBucketLocation",
"s3:GetBucketNotification",
"s3:PutBucketNotification",
"s3:ListAllMyBuckets"
],
"Resource": "arn:aws:s3:::*"
},
{
"Sid": "AddPermissionToFunctionPolicy",
"Effect": "Allow",
"Action": [
"lambda:AddPermission",
"lambda:RemovePermission"
],
"Resource": "arn:aws:lambda:region:account-id:function:*"
}
]
}
257
Amazon SNS
The console lists Amazon Simple Notification Service (Amazon SNS) topics in your account. After you
select a topic, AWS Lambda subscribes your Lambda function to that Amazon SNS topic. For this work,
you need to grant the following additional permissions:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "SNSPerms",
"Effect": "Allow",
"Action": [
"sns:ListSubscriptions",
"sns:ListSubscriptionsByTopic",
"sns:ListTopics",
"sns:Subscribe",
"sns:Unsubscribe"
],
"Resource": "arn:aws:sns:region:account-id:*"
},
{
"Sid": "AddPermissionToFunctionPolicy",
"Effect": "Allow",
"Action": [
"lambda:AddPermission",
"lambda:RemovePermission",
"lambda:GetPolicy"
],
"Resource": "arn:aws:lambda:region:account-id:function:*"
},
{
"Sid": "LambdaListESMappingsPerms",
"Effect": "Allow",
"Action": [
"lambda:ListEventSourceMappings"
],
"Resource": "*"
}
]
}
AWS IoT
The console lists all of the AWS IoT rules. After you select a rule, the console populates the rest of the
information associated with that rule in the user interface. If you select an existing rule, the console updates
it with information so that events are sent to AWS Lambda. You can also create a new rule. To do these
things, the user must have the following additional permissions:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "IoTperms",
"Effect": "Allow",
"Action": [
258
Important
Before you create resource-based policies, we recommend that you first review the introductory
topics that explain the basic concepts and options available for you to manage access to your
AWS Lambda resources. For more information, see Overview of Managing Access Permissions
to Your AWS Lambda Resources (p. 242).
Lambda function policies are primarily used when you are setting up an event source in AWS Lambda
to grant a service or an event source permissions to invoke your Lambda function (see Invoke (p. 304)).
An exception to this is when an event source (for example, Amazon DynamoDB or Amazon Kinesis) uses
the pull model, where permissions are managed in the Lambda function execution role instead. For more
information, see Event Source Mapping (p. 10).
Lambda function policies also make it easy to grant cross-account permissions to invoke your Lambda
function. Suppose you want to grant cross-account permissions (for example, permissions to Amazon
S3) to invoke your Lambda function. Instead of creating an IAM role to grant cross-account permissions,
you can add the relevant permissions in a Lambda function policy.
Note
If the custom application and the Lambda function it invokes belong to the same AWS account,
you don't need to grant explicit permissions using the policy attached to the Lambda function.
259
AWS Lambda provides the following API operations to manage a permissions policy associated with a
Lambda function:
AddPermission (p. 273)
GetPolicy (p. 302)
RemovePermission (p. 322)
Note
The AWS Lambda console is the easiest way to manage event sources and their permissions
in a Lambda function policy. If the AWS service console for the event source supports configuring
event source mapping, you can use that console too. As you configure new event sources or
modify existing event sources, the console automatically modifies the permissions policy
associated with the Lambda function.
The console doesn't support directly modifying permissions in a function policy. You must use either the
AWS CLI or the AWS SDKs. The following are AWS CLI examples of the API operations listed earlier in
this topic:
Examples
Example 1: Allow Amazon S3 to Invoke a Lambda Function (p. 260)
Example 2: Allow Amazon API Gateway to Invoke a Lambda Function (p. 261)
Example 3: Allow a User Application Created by Another AWS Account to Invoke a Lambda Function
(Cross-Account Scenario) (p. 262)
Example 4: Retrieve a Lambda Function Policy (p. 262)
Example 5: Remove Permissions from a Lambda Function Policy (p. 263)
Example 6: Working with Lambda Function Versioning, Aliases, and Permissions (p. 263)
260
--action lambda:InvokeFunction \
--source-arn arn:aws:s3:::examplebucket \
--source-account 111111111111 \
--profile adminuser
The example assumes that the adminuser (who has full permissions) is adding this permission.Therefore,
the --profile parameter specifies the adminuser profile.
In response, AWS Lambda returns the following JSON code. The Statement value is a JSON string
version of the statement added to the Lambda function policy.
{
"Statement": "{\"Condition\":{\"StringEquals\":{\"AWS:SourceAc
count\":\"111111111111\"},
\"ArnLike\":{\"AWS:SourceArn\":\"arn:aws:s3:::examplebuck
et\"}},
\"Action\":[\"lambda:InvokeFunction\"],
\"Resource\":\"arn:aws:lambda:us-west-2:111111111111:func
tion:helloworld\",
\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"s3.amazon
aws.com\"},
\"Sid\":\"1\"}"
}
For information about the push model, see Event Source Mapping (p. 10).
In response, AWS Lambda returns the following JSON code. The Statement value is a JSON string
version of the statement added to the Lambda function policy.
261
{
"Statement": "{\"Condition\":{\"ArnLike\":{\"AWS:SourceArn\":\"arn:aws:apig
ateway:us-east-1::my-api-id:/test/petstorewalkthrough/pets\"}},
\"Action\":[\"lambda:InvokeFunction\"],
\"Resource\":\"arn:aws:lambda:us-west-2:account-id:function:hel
loworld\",
\"Effect\":\"Allow\",
\"Principal\":{\"Service\":\"apigateway.amazonaws.com\"},
\"Sid\":\"5\"}"
}
In response, AWS Lambda returns the following JSON code. The Statement value is a JSON string
version of the statement added to the Lambda function policy.
{
"Statement": "{\"Action\":[\"lambda:InvokeFunction\"],
\"Resource\":\"arn:aws:lambda:us-west-2:account-id:func
tion:helloworld\",
\"Effect\":\"Allow\",
\"Principal\":{\"AWS\":\"account-id\"},
\"Sid\":\"3\"}"
}
262
Note
Permissions for the AWS Lambda Invoke API in the following table can also be granted by
using resource-based policies. For more information, see Using Resource-Based Policies for
AWS Lambda (Lambda Function Policies) (p. 259).
You can use AWS-wide condition keys in your AWS Lambda policies to express conditions. For a complete
list of AWS-wide keys, see Available Keys for Conditions in the IAM User Guide.
Note
To specify an action, use the lambda: prefix followed by the API operation name (for example,
lambda:CreateFunction).
AWS Lambda API and Required Permissions for Actions
AddPermission (p. 273)
Action(s): lambda:AddPermission
Resource: arn:aws:lambda:region:account-id:?/*
CreateEventSourceMapping (p. 279)
Action(s): lambda:CreateEventSourceMapping
Resource: arn:aws:lambda:region:account-id:?
CreateFunction (p. 283)
Action(s): lambda:CreateFunction
263
Resource: arn:aws:lambda:region:account-id:?
DeleteEventSourceMapping (p. 289)
Action(s): lambda:DeleteEventSourceMapping
Resource: arn:aws:lambda:region:account-id:?
DeleteFunction (p. 291)
Action(s): lambda:DeleteFunction,
Resource: arn:aws:lambda:region:account-id:?
GetEventSourceMapping (p. 295)
Action(s): lambda:GetEventSourceMapping
Resource: arn:aws:lambda:region:account-id:?
GetFunction (p. 297)
Action(s): lambda:GetFunction
Resource: arn:aws:lambda:region:account-id:?
GetFunctionConfiguration (p. 299)
Action(s): lambda:DescribeMountTargetSecurityGroups,
Resource: arn:aws:lambda:region:account-id:?
GetPolicy (p. 302)
Action(s): lambda:DescribeMountTargets
Resource: arn:aws:lambda:region:account-id:?
Invoke (p. 304)
Action(s): lambda:DescribeTags
Resource: arn:aws:lambda:region:account-id:?
InvokeAsync (p. 308)
Action(s): lambda:ModifyMountTargetSecurityGroups
Resource: arn:aws:lambda:region:account-id:?
ListEventSourceMappings (p. 312)
Action(s): lambda:ListEventSourceMappings
Resource: arn:aws:lambda:region:account-id:?
ListFunctions (p. 314)
Action(s): lambda:ListFunctions
Resource: arn:aws:lambda:region:account-id:?
RemovePermission (p. 322)
Action(s): lambda:RemovePermission
Resource: arn:aws:lambda:region:account-id:?
UpdateEventSourceMapping (p. 326)
Action(s): lambda:UpdateEventSourceMapping
Resource: arn:aws:lambda:region:account-id:?
UpdateFunctionCode (p. 329)
Action(s): lambda:UpdateFunctionCode
Resource: arn:aws:lambda:region:account-id:?
UpdateFunctionConfiguration (p. 333)
Action(s): lambda:UpdateFunctionConfiguration
264
Resource: arn:aws:lambda:region:account-id:?
Policy Templates
When you create an AWS Lambda function in the console using one of the blueprints, Lambda allows
you to create a role for your function from a list of Lambda policy templates.
By selecting one of these templates, your Lambda function automatically creates the role with the requisite
permissions attached to that policy.
The following lists the permissions that are applied to each policy template in the Policy templates list.
The policy templates are named after the blueprints to which they correspond. Lambda will automatically
populate the placeholder items (such as region and accountID) with the appropriate information. For more
information on creating a Lambda function using policy templates, see Step 2.1: Create a Hello World
Lambda Function (p. 39).
265
]
}
266
267
268
"Effect": "Allow",
"Action": [
"dynamodb:PutItem"
],
"Resource": "arn:aws:dynamodb:region:accountId:table/*"
},
{
"Effect": "Allow",
"Action": [
"lambda:Invoke"
],
"Resource": "arn:aws:lambda:region:accountId:function:*"
}
]
}
269
}
]
}
270
API Reference
This section contains the AWS Lambda API Reference documentation. When making the API calls, you
will need to authenticate your request by providing a signature. AWS Lambda supports signature version
4. For more information, see Signature Version 4 Signing Process in the Amazon Web Services General
Reference.
For an overview of the service, see What Is AWS Lambda? (p. 1). For information about how the service
works, see How It Works (p. 3).
You can use the AWS CLI to explore the AWS Lambda API. This guide provides several tutorials that
use the AWS CLI.
Topics
Actions (p. 271)
Data Types (p. 337)
Actions
The following actions are supported:
AddPermission (p. 273)
CreateAlias (p. 276)
CreateEventSourceMapping (p. 279)
CreateFunction (p. 283)
DeleteAlias (p. 288)
DeleteEventSourceMapping (p. 289)
DeleteFunction (p. 291)
GetAlias (p. 293)
GetEventSourceMapping (p. 295)
GetFunction (p. 297)
GetFunctionConfiguration (p. 299)
GetPolicy (p. 302)
Invoke (p. 304)
271
272
AddPermission
Adds a permission to the resource policy associated with the specified AWS Lambda function. You use
resource policies to grant permissions to event sources that use push model. In a push model, event
sources (such as Amazon S3 and custom applications) invoke your Lambda function. Each permission
you add to the resource policy allows an event source, permission to invoke the Lambda function.
For information about the push model, see AWS Lambda: How it Works.
If you are using versioning, the permissions you add are specific to the Lambda function version or alias
you specify in the AddPermission request via the Qualifier parameter. For more information about
versioning, see AWS Lambda Function Versioning and Aliases.
This operation requires permission for the lambda:AddPermission action.
Request Syntax
POST /2015-03-31/functions/FunctionName/policy?Qualifier=Qualifier HTTP/1.1
Content-type: application/json
{
"Action (p. 274)": "string",
"EventSourceToken (p. 274)": "string",
"Principal (p. 274)": "string",
"SourceAccount (p. 274)": "string",
"SourceArn (p. 274)": "string",
"StatementId (p. 274)": "string"
}
273
Request Body
The request requires the following data in JSON format.
Action (p. 273)
The AWS Lambda action you want to allow in this statement. Each Lambda action is a string starting
with lambda: followed by the API name (see Actions) . For example, lambda:CreateFunction.
You can use wildcard (lambda:*) to grant permission for all AWS Lambda actions.
Type: String
Pattern: (lambda:[*]|lambda:[a-zA-Z]+|[*])
Required: Yes
EventSourceToken (p. 273)
A unique token that must be supplied by the principal invoking the function. This is currently only
used for Alexa Smart Home functions.
Type: String
Length Constraints: Minimum length of 0. Maximum length of 256.
Pattern: [a-zA-Z0-9._\-]+
Required: No
Principal (p. 273)
The principal who is getting this permission. It can be Amazon S3 service Principal
(s3.amazonaws.com) if you want Amazon S3 to invoke the function, an AWS account ID if you are
granting cross-account permission, or any valid AWS service principal such as sns.amazonaws.com.
For example, you might want to allow a custom application in another AWS account to push events
to AWS Lambda by invoking your function.
Type: String
Pattern: .*
Required: Yes
SourceAccount (p. 273)
This parameter is used for S3, SES, CloudWatch Logs and CloudWatch Rules only. The AWS account
ID (without a hyphen) of the source owner. For example, if the SourceArn identifies a bucket, then
this is the bucket owner's account ID. You can use this additional condition to ensure the bucket you
specify is owned by a specific account (it is possible the bucket owner deleted the bucket and some
other AWS account created the bucket). You can also use this condition to specify all sources (that
is, you don't specify the SourceArn) owned by a specific account.
Type: String
Pattern: \d{12}
Required: No
SourceArn (p. 273)
This is optional; however, when granting Amazon S3 permission to invoke your function, you should
specify this field with the Amazon Resource Name (ARN) as its value. This ensures that only events
generated from the specified source can invoke the function.
Important
If you add a permission for the Amazon S3 principal without providing the source ARN, any
AWS account that creates a mapping to your function ARN can send events to invoke your
Lambda function from Amazon S3.
Type: String
Pattern: arn:aws:([a-zA-Z0-9\-])+:([a-z]{2}-[a-z]+-\d{1})?:(\d{12})?:(.*)
Required: No
StatementId (p. 273)
A unique statement identifier.
Type: String
Length Constraints: Minimum length of 1. Maximum length of 100.
274
Pattern: ([a-zA-Z0-9-_]+)
Required: Yes
Response Syntax
HTTP/1.1 201
Content-type: application/json
{
"Statement (p. 275)": "string"
}
Response Elements
If the action is successful, the service sends back an HTTP 201 response.
The following data is returned in JSON format by the service.
Statement (p. 275)
The permission statement you specified in the request. The response returns the same as a string
using a backslash ("\") as an escape character in the JSON.
Type: String
Errors
InvalidParameterValueException
One of the parameters in the request is invalid. For example, if you provided an IAM role for AWS
Lambda to assume in the CreateFunction or the UpdateFunctionConfiguration API, that
AWS Lambda is unable to assume you will get this exception.
HTTP Status Code: 400
PolicyLengthExceededException
Lambda function access policy is limited to 20 KB.
HTTP Status Code: 400
ResourceConflictException
The resource already exists.
HTTP Status Code: 409
ResourceNotFoundException
The resource (for example, a Lambda function or access policy statement) 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
HTTP Status Code: 429
275
CreateAlias
Creates an alias that points to the specified Lambda function version. For more information, see Introduction
to AWS Lambda Aliases.
Alias names are unique for a given function. This requires permission for the lambda:CreateAlias action.
Request Syntax
POST /2015-03-31/functions/FunctionName/aliases HTTP/1.1
Content-type: application/json
{
"Description (p. 276)": "string",
"FunctionVersion (p. 276)": "string",
"Name (p. 276)": "string"
}
Request Body
The request requires the following data in JSON format.
Description (p. 276)
Description of the alias.
Type: String
Length Constraints: Minimum length of 0. Maximum length of 256.
Required: No
FunctionVersion (p. 276)
Lambda function version for which you are creating the alias.
Type: String
Length Constraints: Minimum length of 1. Maximum length of 1024.
Pattern: (\$LATEST|[0-9]+)
Required: Yes
Name (p. 276)
Name for the alias you are creating.
Type: String
Length Constraints: Minimum length of 1. Maximum length of 128.
Pattern: (?!^[0-9]+$)([a-zA-Z0-9-_]+)
Required: Yes
276
Response Syntax
HTTP/1.1 201
Content-type: application/json
{
"AliasArn (p. 277)": "string",
"Description (p. 277)": "string",
"FunctionVersion (p. 277)": "string",
"Name (p. 277)": "string"
}
Response Elements
If the action is successful, the service sends back an HTTP 201 response.
The following data is returned in JSON format by the service.
AliasArn (p. 277)
Lambda function ARN that is qualified using the alias name as the suffix. For example, if you create
an alias called BETA that points to a helloworld function version, the ARN is
arn:aws:lambda:aws-regions:acct-id:function:helloworld:BETA.
Type: String
Pattern:
arn:aws:lambda:[a-z]{2}-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_]+(:(\$LATEST|[a-zA-Z0-9-_]+))?
Description (p. 277)
Alias description.
Type: String
Length Constraints: Minimum length of 0. Maximum length of 256.
FunctionVersion (p. 277)
Function version to which the alias points.
Type: String
Length Constraints: Minimum length of 1. Maximum length of 1024.
Pattern: (\$LATEST|[0-9]+)
Name (p. 277)
Alias name.
Type: String
Length Constraints: Minimum length of 1. Maximum length of 128.
Pattern: (?!^[0-9]+$)([a-zA-Z0-9-_]+)
Errors
InvalidParameterValueException
One of the parameters in the request is invalid. For example, if you provided an IAM role for AWS
Lambda to assume in the CreateFunction or the UpdateFunctionConfiguration API, that
AWS Lambda is unable to assume you will get this exception.
HTTP Status Code: 400
ResourceConflictException
The resource already exists.
HTTP Status Code: 409
277
ResourceNotFoundException
The resource (for example, a Lambda function or access policy statement) 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
HTTP Status Code: 429
278
CreateEventSourceMapping
Identifies a stream as an event source for a Lambda function. It can be either an Amazon Kinesis stream
or an Amazon DynamoDB stream. AWS Lambda invokes the specified function when records are posted
to the stream.
This association between a stream source and a Lambda function is called the event source mapping.
Important
This event source mapping is relevant only in the AWS Lambda pull model, where AWS Lambda
invokes the function. For more information, go to AWS Lambda: How it Works in the AWS Lambda
Developer Guide.
You provide mapping information (for example, which stream to read from and which Lambda function
to invoke) in the request body.
Each event source, such as an Amazon Kinesis or a DynamoDB stream, can be associated with multiple
AWS Lambda function. A given Lambda function can be associated with multiple AWS event sources.
If you are using versioning, you can specify a specific function version or an alias via the function name
parameter. For more information about versioning, see AWS Lambda Function Versioning and Aliases.
This operation requires permission for the lambda:CreateEventSourceMapping action.
Request Syntax
POST /2015-03-31/event-source-mappings/ HTTP/1.1
Content-type: application/json
{
"BatchSize (p. 279)": number,
"Enabled (p. 279)": boolean,
"EventSourceArn (p. 279)": "string",
"FunctionName (p. 280)": "string",
"StartingPosition (p. 280)": "string"
}
Request Body
The request requires the following data in JSON format.
BatchSize (p. 279)
The largest number of records that AWS Lambda will retrieve from your event source at the time of
invoking your function. Your function receives an event with all the retrieved records. The default is
100 records.
Type: Integer
Valid Range: Minimum value of 1. Maximum value of 10000.
Required: No
Enabled (p. 279)
Indicates whether AWS Lambda should begin polling the event source. By default, Enabled is true.
Type: Boolean
Required: No
EventSourceArn (p. 279)
The Amazon Resource Name (ARN) of the Amazon Kinesis or the Amazon DynamoDB stream that
is the event source. Any record added to this stream could cause AWS Lambda to invoke your
279
Lambda function, it depends on the BatchSize. AWS Lambda POSTs the Amazon Kinesis event,
containing records, to your Lambda function as JSON.
Type: String
Pattern: arn:aws:([a-zA-Z0-9\-])+:([a-z]{2}-[a-z]+-\d{1})?:(\d{12})?:(.*)
Required: Yes
FunctionName (p. 279)
The Lambda function to invoke when AWS Lambda detects an event on the stream.
You can specify the function name (for example, Thumbnail) or you can specify Amazon Resource
Name (ARN) of the function (for example,
arn:aws:lambda:us-west-2:account-id:function:ThumbNail).
If you are using versioning, you can also provide a qualified function ARN (ARN that is qualified with
function version or alias name as suffix). For more information about versioning, see AWS Lambda
Function Versioning and Aliases
AWS Lambda also allows you to specify only the function name with the account ID qualifier (for
example, account-id:Thumbnail).
Note that the length constraint applies only to the ARN. If you specify only the function name, it is
limited to 64 character in length.
Type: String
Length Constraints: Minimum length of 1. Maximum length of 140.
Pattern:
(arn:aws:lambda:)?([a-z]{2}-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?
Required: Yes
StartingPosition (p. 279)
The position in the stream where AWS Lambda should start reading. For more information, go to
ShardIteratorType in the Amazon Kinesis API Reference.
Type: String
Valid Values: TRIM_HORIZON | LATEST
Required: Yes
Response Syntax
HTTP/1.1 202
Content-type: application/json
{
"BatchSize (p. 281)": number,
"EventSourceArn (p. 281)": "string",
"FunctionArn (p. 281)": "string",
"LastModified (p. 281)": number,
"LastProcessingResult (p. 281)": "string",
"State (p. 281)": "string",
"StateTransitionReason (p. 281)": "string",
"UUID (p. 281)": "string"
}
Response Elements
If the action is successful, the service sends back an HTTP 202 response.
The following data is returned in JSON format by the service.
280
Errors
InvalidParameterValueException
One of the parameters in the request is invalid. For example, if you provided an IAM role for AWS
Lambda to assume in the CreateFunction or the UpdateFunctionConfiguration API, that
AWS Lambda is unable to assume you will get this exception.
HTTP Status Code: 400
ResourceConflictException
The resource already exists.
HTTP Status Code: 409
ResourceNotFoundException
The resource (for example, a Lambda function or access policy statement) specified in the request
does not exist.
HTTP Status Code: 404
ServiceException
The AWS Lambda service encountered an internal error.
HTTP Status Code: 500
281
TooManyRequestsException
HTTP Status Code: 429
282
CreateFunction
Creates a new Lambda function. The function metadata is created from the request parameters, and the
code for the function is provided by a .zip file in the request body. If the function name already exists, the
operation will fail. Note that the function name is case-sensitive.
If you are using versioning, you can also publish a version of the Lambda function you are creating using
the Publish parameter. For more information about versioning, see AWS Lambda Function Versioning
and Aliases.
This operation requires permission for the lambda:CreateFunction action.
Request Syntax
POST /2015-03-31/functions HTTP/1.1
Content-type: application/json
{
"Code (p. 283)": {
"S3Bucket (p. 340)": "string",
"S3Key (p. 340)": "string",
"S3ObjectVersion (p. 340)": "string",
"ZipFile (p. 340)": blob
},
"Description (p. 283)": "string",
"FunctionName (p. 284)": "string",
"Handler (p. 284)": "string",
"MemorySize (p. 284)": number,
"Publish (p. 284)": boolean,
"Role (p. 284)": "string",
"Runtime (p. 284)": "string",
"Timeout (p. 284)": number,
"VpcConfig (p. 285)": {
"SecurityGroupIds (p. 344)": [ "string" ],
"SubnetIds (p. 344)": [ "string" ]
}
}
Request Body
The request requires the following data in JSON format.
Code (p. 283)
The code for the Lambda function.
Type: FunctionCode (p. 340) object
Required: Yes
Description (p. 283)
A short, user-defined function description. Lambda does not use this value. Assign a meaningful
description as you see fit.
Type: String
Length Constraints: Minimum length of 0. Maximum length of 256.
Required: No
283
284
Required: No
VpcConfig (p. 283)
If your Lambda function accesses resources in a VPC, you provide this parameter identifying the list
of security group IDs and subnet IDs. These must belong to the same VPC. You must provide at
least one security group and one subnet ID.
Type: VpcConfig (p. 344) object
Required: No
Response Syntax
HTTP/1.1 201
Content-type: application/json
{
"CodeSha256 (p. 285)": "string",
"CodeSize (p. 285)": number,
"Description (p. 285)": "string",
"FunctionArn (p. 285)": "string",
"FunctionName (p. 286)": "string",
"Handler (p. 286)": "string",
"LastModified (p. 286)": "string",
"MemorySize (p. 286)": number,
"Role (p. 286)": "string",
"Runtime (p. 286)": "string",
"Timeout (p. 286)": number,
"Version (p. 286)": "string",
"VpcConfig (p. 286)": {
"SecurityGroupIds (p. 345)": [ "string" ],
"SubnetIds (p. 345)": [ "string" ],
"VpcId (p. 345)": "string"
}
}
Response Elements
If the action is successful, the service sends back an HTTP 201 response.
The following data is returned in JSON format by the service.
CodeSha256 (p. 285)
It is the SHA256 hash of your function deployment package.
Type: String
CodeSize (p. 285)
The size, in bytes, of the function .zip file you uploaded.
Type: Long
Description (p. 285)
The user-provided description.
Type: String
Length Constraints: Minimum length of 0. Maximum length of 256.
FunctionArn (p. 285)
The Amazon Resource Name (ARN) assigned to the function.
Type: String
Pattern:
arn:aws:lambda:[a-z]{2}-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_]+(:(\$LATEST|[a-zA-Z0-9-_]+))?
285
Errors
CodeStorageExceededException
You have exceeded your maximum total code size per account. Limits
HTTP Status Code: 400
286
InvalidParameterValueException
One of the parameters in the request is invalid. For example, if you provided an IAM role for AWS
Lambda to assume in the CreateFunction or the UpdateFunctionConfiguration API, that
AWS Lambda is unable to assume you will get this exception.
HTTP Status Code: 400
ResourceConflictException
The resource already exists.
HTTP Status Code: 409
ResourceNotFoundException
The resource (for example, a Lambda function or access policy statement) 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
HTTP Status Code: 429
287
DeleteAlias
Deletes the specified Lambda function alias. For more information, see Introduction to AWS Lambda
Aliases.
This requires permission for the lambda:DeleteAlias action.
Request Syntax
DELETE /2015-03-31/functions/FunctionName/aliases/Name HTTP/1.1
Request Body
The request does not have a request body.
Response Syntax
HTTP/1.1 204
Response Elements
If the action is successful, the service sends back an HTTP 204 response with an empty HTTP body.
Errors
InvalidParameterValueException
One of the parameters in the request is invalid. For example, if you provided an IAM role for AWS
Lambda to assume in the CreateFunction or the UpdateFunctionConfiguration API, that
AWS Lambda is unable to assume you will get this exception.
HTTP Status Code: 400
ServiceException
The AWS Lambda service encountered an internal error.
HTTP Status Code: 500
TooManyRequestsException
HTTP Status Code: 429
288
DeleteEventSourceMapping
Removes an event source mapping. This means AWS Lambda will no longer invoke the function for
events in the associated source.
This operation requires permission for the lambda:DeleteEventSourceMapping action.
Request Syntax
DELETE /2015-03-31/event-source-mappings/UUID HTTP/1.1
Request Body
The request does not have a request body.
Response Syntax
HTTP/1.1 202
Content-type: application/json
{
"BatchSize (p. 289)": number,
"EventSourceArn (p. 289)": "string",
"FunctionArn (p. 289)": "string",
"LastModified (p. 290)": number,
"LastProcessingResult (p. 290)": "string",
"State (p. 290)": "string",
"StateTransitionReason (p. 290)": "string",
"UUID (p. 290)": "string"
}
Response Elements
If the action is successful, the service sends back an HTTP 202 response.
The following data is returned in JSON format by the service.
BatchSize (p. 289)
The largest number of records that AWS Lambda will retrieve from your event source at the time of
invoking your function. Your function receives an event with all the retrieved records.
Type: Integer
Valid Range: Minimum value of 1. Maximum value of 10000.
EventSourceArn (p. 289)
The Amazon Resource Name (ARN) of the Amazon Kinesis stream that is the source of events.
Type: String
Pattern: arn:aws:([a-zA-Z0-9\-])+:([a-z]{2}-[a-z]+-\d{1})?:(\d{12})?:(.*)
FunctionArn (p. 289)
The Lambda function to invoke when AWS Lambda detects an event on the stream.
289
Type: String
Pattern:
arn:aws:lambda:[a-z]{2}-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_]+(:(\$LATEST|[a-zA-Z0-9-_]+))?
LastModified (p. 289)
The UTC time string indicating the last time the event mapping was updated.
Type: Timestamp
LastProcessingResult (p. 289)
The result of the last AWS Lambda invocation of your Lambda function.
Type: String
State (p. 289)
The state of the event source mapping. It can be Creating, Enabled, Disabled, Enabling,
Disabling, Updating, or Deleting.
Type: String
StateTransitionReason (p. 289)
The reason the event source mapping is in its current state. It is either user-requested or an AWS
Lambda-initiated state transition.
Type: String
UUID (p. 289)
The AWS Lambda assigned opaque identifier for the mapping.
Type: String
Errors
InvalidParameterValueException
One of the parameters in the request is invalid. For example, if you provided an IAM role for AWS
Lambda to assume in the CreateFunction or the UpdateFunctionConfiguration API, that
AWS Lambda is unable to assume you will get this exception.
HTTP Status Code: 400
ResourceNotFoundException
The resource (for example, a Lambda function or access policy statement) 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
HTTP Status Code: 429
290
DeleteFunction
Deletes the specified Lambda function code and configuration.
If you are using the versioning feature and you don't specify a function version in your DeleteFunction
request, AWS Lambda will delete the function, including all its versions, and any aliases pointing to the
function versions. To delete a specific function version, you must provide the function version via the
Qualifier parameter. For information about function versioning, see AWS Lambda Function Versioning
and Aliases.
When you delete a function the associated resource policy is also deleted. You will need to delete the
event source mappings explicitly.
This operation requires permission for the lambda:DeleteFunction action.
Request Syntax
DELETE /2015-03-31/functions/FunctionName?Qualifier=Qualifier HTTP/1.1
Request Body
The request does not have a request body.
291
Response Syntax
HTTP/1.1 204
Response Elements
If the action is successful, the service sends back an HTTP 204 response with an empty HTTP body.
Errors
InvalidParameterValueException
One of the parameters in the request is invalid. For example, if you provided an IAM role for AWS
Lambda to assume in the CreateFunction or the UpdateFunctionConfiguration API, that
AWS Lambda is unable to assume you will get this exception.
HTTP Status Code: 400
ResourceConflictException
The resource already exists.
HTTP Status Code: 409
ResourceNotFoundException
The resource (for example, a Lambda function or access policy statement) 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
HTTP Status Code: 429
292
GetAlias
Returns the specified alias information such as the alias ARN, description, and function version it is
pointing to. For more information, see Introduction to AWS Lambda Aliases.
This requires permission for the lambda:GetAlias action.
Request Syntax
GET /2015-03-31/functions/FunctionName/aliases/Name HTTP/1.1
Request Body
The request does not have a request body.
Response Syntax
HTTP/1.1 200
Content-type: application/json
{
"AliasArn (p. 293)": "string",
"Description (p. 294)": "string",
"FunctionVersion (p. 294)": "string",
"Name (p. 294)": "string"
}
Response Elements
If the action is successful, the service sends back an HTTP 200 response.
The following data is returned in JSON format by the service.
AliasArn (p. 293)
Lambda function ARN that is qualified using the alias name as the suffix. For example, if you create
an alias called BETA that points to a helloworld function version, the ARN is
arn:aws:lambda:aws-regions:acct-id:function:helloworld:BETA.
Type: String
Pattern:
arn:aws:lambda:[a-z]{2}-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_]+(:(\$LATEST|[a-zA-Z0-9-_]+))?
293
Errors
InvalidParameterValueException
One of the parameters in the request is invalid. For example, if you provided an IAM role for AWS
Lambda to assume in the CreateFunction or the UpdateFunctionConfiguration API, that
AWS Lambda is unable to assume you will get this exception.
HTTP Status Code: 400
ResourceNotFoundException
The resource (for example, a Lambda function or access policy statement) 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
HTTP Status Code: 429
294
GetEventSourceMapping
Returns configuration information for the specified event source mapping (see
CreateEventSourceMapping (p. 279)).
This operation requires permission for the lambda:GetEventSourceMapping action.
Request Syntax
GET /2015-03-31/event-source-mappings/UUID HTTP/1.1
Request Body
The request does not have a request body.
Response Syntax
HTTP/1.1 200
Content-type: application/json
{
"BatchSize (p. 295)": number,
"EventSourceArn (p. 295)": "string",
"FunctionArn (p. 295)": "string",
"LastModified (p. 296)": number,
"LastProcessingResult (p. 296)": "string",
"State (p. 296)": "string",
"StateTransitionReason (p. 296)": "string",
"UUID (p. 296)": "string"
}
Response Elements
If the action is successful, the service sends back an HTTP 200 response.
The following data is returned in JSON format by the service.
BatchSize (p. 295)
The largest number of records that AWS Lambda will retrieve from your event source at the time of
invoking your function. Your function receives an event with all the retrieved records.
Type: Integer
Valid Range: Minimum value of 1. Maximum value of 10000.
EventSourceArn (p. 295)
The Amazon Resource Name (ARN) of the Amazon Kinesis stream that is the source of events.
Type: String
Pattern: arn:aws:([a-zA-Z0-9\-])+:([a-z]{2}-[a-z]+-\d{1})?:(\d{12})?:(.*)
FunctionArn (p. 295)
The Lambda function to invoke when AWS Lambda detects an event on the stream.
295
Type: String
Pattern:
arn:aws:lambda:[a-z]{2}-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_]+(:(\$LATEST|[a-zA-Z0-9-_]+))?
LastModified (p. 295)
The UTC time string indicating the last time the event mapping was updated.
Type: Timestamp
LastProcessingResult (p. 295)
The result of the last AWS Lambda invocation of your Lambda function.
Type: String
State (p. 295)
The state of the event source mapping. It can be Creating, Enabled, Disabled, Enabling,
Disabling, Updating, or Deleting.
Type: String
StateTransitionReason (p. 295)
The reason the event source mapping is in its current state. It is either user-requested or an AWS
Lambda-initiated state transition.
Type: String
UUID (p. 295)
The AWS Lambda assigned opaque identifier for the mapping.
Type: String
Errors
InvalidParameterValueException
One of the parameters in the request is invalid. For example, if you provided an IAM role for AWS
Lambda to assume in the CreateFunction or the UpdateFunctionConfiguration API, that
AWS Lambda is unable to assume you will get this exception.
HTTP Status Code: 400
ResourceNotFoundException
The resource (for example, a Lambda function or access policy statement) 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
HTTP Status Code: 429
296
GetFunction
Returns the configuration information of the Lambda function and a presigned URL link to the .zip file you
uploaded with CreateFunction (p. 283) so you can download the .zip file. Note that the URL is valid for up
to 10 minutes. The configuration information is the same information you provided as parameters when
uploading the function.
Using the optional Qualifier parameter, you can specify a specific function version for which you want
this information. If you don't specify this parameter, the API uses unqualified function ARN which return
information about the $LATEST version of the Lambda function. For more information, see AWS Lambda
Function Versioning and Aliases.
This operation requires permission for the lambda:GetFunction action.
Request Syntax
GET /2015-03-31/functions/FunctionName?Qualifier=Qualifier HTTP/1.1
Request Body
The request does not have a request body.
Response Syntax
HTTP/1.1 200
Content-type: application/json
{
"Code (p. 298)": {
"Location (p. 341)": "string",
"RepositoryType (p. 341)": "string"
297
},
"Configuration (p. 298)": {
"CodeSha256 (p. 342)": "string",
"CodeSize (p. 342)": number,
"Description (p. 342)": "string",
"FunctionArn (p. 342)": "string",
"FunctionName (p. 342)": "string",
"Handler (p. 342)": "string",
"LastModified (p. 342)": "string",
"MemorySize (p. 342)": number,
"Role (p. 342)": "string",
"Runtime (p. 343)": "string",
"Timeout (p. 343)": number,
"Version (p. 343)": "string",
"VpcConfig (p. 343)": {
"SecurityGroupIds (p. 345)": [ "string" ],
"SubnetIds (p. 345)": [ "string" ],
"VpcId (p. 345)": "string"
}
}
}
Response Elements
If the action is successful, the service sends back an HTTP 200 response.
The following data is returned in JSON format by the service.
Code (p. 297)
The object for the Lambda function location.
Type: FunctionCodeLocation (p. 341) object
Configuration (p. 297)
A complex type that describes function metadata.
Type: FunctionConfiguration (p. 342) object
Errors
InvalidParameterValueException
One of the parameters in the request is invalid. For example, if you provided an IAM role for AWS
Lambda to assume in the CreateFunction or the UpdateFunctionConfiguration API, that
AWS Lambda is unable to assume you will get this exception.
HTTP Status Code: 400
ResourceNotFoundException
The resource (for example, a Lambda function or access policy statement) 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
HTTP Status Code: 429
298
GetFunctionConfiguration
Returns the configuration information of the Lambda function. This the same information you provided
as parameters when uploading the function by using CreateFunction (p. 283).
If you are using the versioning feature, you can retrieve this information for a specific function version by
using the optional Qualifier parameter and specifying the function version or alias that points to it. If
you don't provide it, the API returns information about the $LATEST version of the function. For more
information about versioning, see AWS Lambda Function Versioning and Aliases.
This operation requires permission for the lambda:GetFunctionConfiguration operation.
Request Syntax
GET /2015-03-31/functions/FunctionName/configuration?Qualifier=Qualifier HTTP/1.1
Request Body
The request does not have a request body.
Response Syntax
HTTP/1.1 200
Content-type: application/json
{
"CodeSha256 (p. 300)": "string",
"CodeSize (p. 300)": number,
"Description (p. 300)": "string",
"FunctionArn (p. 300)": "string",
"FunctionName (p. 300)": "string",
299
Response Elements
If the action is successful, the service sends back an HTTP 200 response.
The following data is returned in JSON format by the service.
CodeSha256 (p. 299)
It is the SHA256 hash of your function deployment package.
Type: String
CodeSize (p. 299)
The size, in bytes, of the function .zip file you uploaded.
Type: Long
Description (p. 299)
The user-provided description.
Type: String
Length Constraints: Minimum length of 0. Maximum length of 256.
FunctionArn (p. 299)
The Amazon Resource Name (ARN) assigned to the function.
Type: String
Pattern:
arn:aws:lambda:[a-z]{2}-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_]+(:(\$LATEST|[a-zA-Z0-9-_]+))?
FunctionName (p. 299)
The name of the function.
Type: String
Length Constraints: Minimum length of 1. Maximum length of 140.
Pattern:
(arn:aws:lambda:)?([a-z]{2}-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?
Handler (p. 299)
The function Lambda calls to begin executing your function.
Type: String
Length Constraints: Maximum length of 128.
Pattern: [^\s]+
LastModified (p. 299)
The time stamp of the last time you updated the function.
Type: String
MemorySize (p. 299)
The memory size, in MB, you configured for the function. Must be a multiple of 64 MB.
Type: Integer
300
Errors
InvalidParameterValueException
One of the parameters in the request is invalid. For example, if you provided an IAM role for AWS
Lambda to assume in the CreateFunction or the UpdateFunctionConfiguration API, that
AWS Lambda is unable to assume you will get this exception.
HTTP Status Code: 400
ResourceNotFoundException
The resource (for example, a Lambda function or access policy statement) 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
HTTP Status Code: 429
301
GetPolicy
Returns the resource policy associated with the specified Lambda function.
If you are using the versioning feature, you can get the resource policy associated with the specific Lambda
function version or alias by specifying the version or alias name using the Qualifier parameter. For
more information about versioning, see AWS Lambda Function Versioning and Aliases.
For information about adding permissions, see AddPermission (p. 273).
You need permission for the lambda:GetPolicy action.
Request Syntax
GET /2015-03-31/functions/FunctionName/policy?Qualifier=Qualifier HTTP/1.1
Request Body
The request does not have a request body.
Response Syntax
HTTP/1.1 200
Content-type: application/json
{
"Policy (p. 303)": "string"
}
Response Elements
If the action is successful, the service sends back an HTTP 200 response.
The following data is returned in JSON format by the service.
302
Errors
InvalidParameterValueException
One of the parameters in the request is invalid. For example, if you provided an IAM role for AWS
Lambda to assume in the CreateFunction or the UpdateFunctionConfiguration API, that
AWS Lambda is unable to assume you will get this exception.
HTTP Status Code: 400
ResourceNotFoundException
The resource (for example, a Lambda function or access policy statement) 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
HTTP Status Code: 429
303
Invoke
Invokes a specific Lambda function. For an example, see Create the Lambda Function and Test It Manually.
If you are using the versioning feature, you can invoke the specific function version by providing function
version or alias name that is pointing to the function version using the Qualifier parameter in the
request. If you don't provide the Qualifier parameter, the $LATEST version of the Lambda function is
invoked. Invocations occur at least once in response to an event and functions must be idempotent to
handle this. For information about the versioning feature, see AWS Lambda Function Versioning and
Aliases.
This operation requires permission for the lambda:InvokeFunction action.
Request Syntax
POST /2015-03-31/functions/FunctionName/invocations?Qualifier=Qualifier HTTP/1.1
X-Amz-Invocation-Type: InvocationType
X-Amz-Log-Type: LogType
X-Amz-Client-Context: ClientContext
Payload
304
Request Body
The request requires the following data in JSON format.
Payload (p. 304)
JSON that you want to provide to your Lambda function as input.
Type: Binary data
Required: No
Response Syntax
HTTP/1.1 StatusCode
X-Amz-Function-Error: FunctionError
X-Amz-Log-Result: LogResult
Payload
Response Elements
If the action is successful, the service sends back the following HTTP response.
StatusCode (p. 305)
The HTTP status code will be in the 200 range for successful request. For the RequestResonse
invocation type this status code will be 200. For the Event invocation type this status code will be
202. For the DryRun invocation type the status code will be 204.
The response returns the following HTTP headers.
FunctionError (p. 305)
Indicates whether an error occurred while executing the Lambda function. If an error occurred this
field will have one of two values; Handled or Unhandled. Handled errors are errors that are reported
by the function while the Unhandled errors are those detected and reported by AWS Lambda.
Unhandled errors include out of memory errors and function timeouts. For information about how to
report an Handled error, see Programming Model.
LogResult (p. 305)
It is the base64-encoded logs for the Lambda function invocation.This is present only if the invocation
type is RequestResponse and the logs were requested.
The response returns the following as the HTTP body.
<varlistentry> Payload (p. 305)
It is the JSON representation of the object returned by the Lambda function. This is present only if the
invocation type is RequestResponse.
305
In the event of a function error this field contains a message describing the error. For the Handled errors
the Lambda function will report this message. For Unhandled errors AWS Lambda reports the message.
</varlistentry>
Errors
EC2AccessDeniedException
HTTP Status Code: 502
EC2ThrottledException
AWS Lambda was throttled by Amazon EC2 during Lambda function initialization using the execution
role provided for the Lambda function.
HTTP Status Code: 502
EC2UnexpectedException
AWS Lambda received an unexpected EC2 client exception while setting up for the Lambda function.
HTTP Status Code: 502
ENILimitReachedException
AWS Lambda was not able to create an Elastic Network Interface (ENI) in the VPC, specified as part
of Lambda function configuration, because the limit for network interfaces has been reached.
HTTP Status Code: 502
InvalidParameterValueException
One of the parameters in the request is invalid. For example, if you provided an IAM role for AWS
Lambda to assume in the CreateFunction or the UpdateFunctionConfiguration API, that
AWS Lambda is unable to assume you will get this exception.
HTTP Status Code: 400
InvalidRequestContentException
The request body could not be parsed as JSON.
HTTP Status Code: 400
InvalidSecurityGroupIDException
The Security Group ID provided in the Lambda function VPC configuration is invalid.
HTTP Status Code: 502
InvalidSubnetIDException
The Subnet ID provided in the Lambda function VPC configuration is invalid.
HTTP Status Code: 502
InvalidZipFileException
HTTP Status Code: 502
RequestTooLargeException
The request payload exceeded the Invoke request body JSON input limit. For more information,
see Limits.
HTTP Status Code: 413
ResourceNotFoundException
The resource (for example, a Lambda function or access policy statement) specified in the request
does not exist.
HTTP Status Code: 404
ServiceException
The AWS Lambda service encountered an internal error.
HTTP Status Code: 500
SubnetIPAddressLimitReachedException
AWS Lambda was not able to set up VPC access for the Lambda function because one or more
configured subnets has no available IP addresses.
HTTP Status Code: 502
306
TooManyRequestsException
HTTP Status Code: 429
UnsupportedMediaTypeException
The content type of the Invoke request body is not JSON.
HTTP Status Code: 415
307
InvokeAsync
Important
This API is deprecated. We recommend you use Invoke API (see Invoke (p. 304)).
Submits an invocation request to AWS Lambda. Upon receiving the request, Lambda executes the
specified function asynchronously. To see the logs generated by the Lambda function execution, see the
CloudWatch Logs console.
This operation requires permission for the lambda:InvokeFunction action.
Request Syntax
POST /2014-11-13/functions/FunctionName/invoke-async/ HTTP/1.1
InvokeArgs
Request Body
The request requires the following data in JSON format.
InvokeArgs (p. 308)
JSON that you want to provide to your Lambda function as input.
Type: Binary data
Required: Yes
Response Syntax
HTTP/1.1 Status
Response Elements
If the action is successful, the service sends back the following HTTP response.
Status (p. 308)
It will be 202 upon success.
Errors
InvalidRequestContentException
The request body could not be parsed as JSON.
HTTP Status Code: 400
308
ResourceNotFoundException
The resource (for example, a Lambda function or access policy statement) specified in the request
does not exist.
HTTP Status Code: 404
ServiceException
The AWS Lambda service encountered an internal error.
HTTP Status Code: 500
Example
Invoke a Lambda function
The following example uses a POST request to invoke a Lambda function.
Sample Request
POST /2014-11-13/functions/helloworld/invoke-async/ HTTP/1.1
[input json]
Sample Response
HTTP/1.1 202 Accepted
x-amzn-requestid: f037bc5c-5a08-11e4-b02e-af446c3f9d0d
content-length: 0
connection: keep-alive
date: Wed, 22 Oct 2014 16:31:55 GMT
content-type: application/json
309
ListAliases
Returns list of aliases created for a Lambda function. For each alias, the response includes information
such as the alias ARN, description, alias name, and the function version to which it points. For more
information, see Introduction to AWS Lambda Aliases.
This requires permission for the lambda:ListAliases action.
Request Syntax
GET /2015-03-31/functions/FunctionName/aliases?FunctionVersion=FunctionVer
sion&Marker=Marker&MaxItems=MaxItems HTTP/1.1
Request Body
The request does not have a request body.
Response Syntax
HTTP/1.1 200
Content-type: application/json
{
"Aliases (p. 311)": [
{
"AliasArn (p. 338)": "string",
"Description (p. 338)": "string",
"FunctionVersion (p. 338)": "string",
"Name (p. 338)": "string"
}
],
310
Response Elements
If the action is successful, the service sends back an HTTP 200 response.
The following data is returned in JSON format by the service.
Aliases (p. 310)
A list of aliases.
Type: array of AliasConfiguration (p. 338) objects
NextMarker (p. 310)
A string, present if there are more aliases.
Type: String
Errors
InvalidParameterValueException
One of the parameters in the request is invalid. For example, if you provided an IAM role for AWS
Lambda to assume in the CreateFunction or the UpdateFunctionConfiguration API, that
AWS Lambda is unable to assume you will get this exception.
HTTP Status Code: 400
ResourceNotFoundException
The resource (for example, a Lambda function or access policy statement) 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
HTTP Status Code: 429
311
ListEventSourceMappings
Returns a list of event source mappings you created using the CreateEventSourceMapping (see
CreateEventSourceMapping (p. 279)).
For each mapping, the API returns configuration information. You can optionally specify filters to retrieve
specific event source mappings.
If you are using the versioning feature, you can get list of event source mappings for a specific Lambda
function version or an alias as described in the FunctionName parameter. For information about the
versioning feature, see AWS Lambda Function Versioning and Aliases.
This operation requires permission for the lambda:ListEventSourceMappings action.
Request Syntax
GET /2015-03-31/event-source-mappings/?EventSourceArn=EventSourceArn&Function
Name=FunctionName&Marker=Marker&MaxItems=MaxItems HTTP/1.1
Request Body
The request does not have a request body.
Response Syntax
HTTP/1.1 200
Content-type: application/json
312
{
"EventSourceMappings (p. 313)": [
{
"BatchSize (p. 339)": number,
"EventSourceArn (p. 339)": "string",
"FunctionArn (p. 339)": "string",
"LastModified (p. 339)": number,
"LastProcessingResult (p. 339)": "string",
"State (p. 339)": "string",
"StateTransitionReason (p. 339)": "string",
"UUID (p. 339)": "string"
}
],
"NextMarker (p. 313)": "string"
}
Response Elements
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 (p. 312)
An array of EventSourceMappingConfiguration objects.
Type: array of EventSourceMappingConfiguration (p. 339) objects
NextMarker (p. 312)
A string, present if there are more event source mappings.
Type: String
Errors
InvalidParameterValueException
One of the parameters in the request is invalid. For example, if you provided an IAM role for AWS
Lambda to assume in the CreateFunction or the UpdateFunctionConfiguration API, that
AWS Lambda is unable to assume you will get this exception.
HTTP Status Code: 400
ResourceNotFoundException
The resource (for example, a Lambda function or access policy statement) 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
HTTP Status Code: 429
313
ListFunctions
Returns a list of your Lambda functions. For each function, the response includes the function configuration
information. You must use GetFunction (p. 297) to retrieve the code for your function.
This operation requires permission for the lambda:ListFunctions action.
If you are using versioning feature, the response returns list of $LATEST versions of your functions. For
information about the versioning feature, see AWS Lambda Function Versioning and Aliases.
Request Syntax
GET /2015-03-31/functions/?Marker=Marker&MaxItems=MaxItems HTTP/1.1
Request Body
The request does not have a request body.
Response Syntax
HTTP/1.1 200
Content-type: application/json
{
"Functions (p. 315)": [
{
"CodeSha256 (p. 342)": "string",
"CodeSize (p. 342)": number,
"Description (p. 342)": "string",
"FunctionArn (p. 342)": "string",
"FunctionName (p. 342)": "string",
"Handler (p. 342)": "string",
"LastModified (p. 342)": "string",
"MemorySize (p. 342)": number,
"Role (p. 342)": "string",
"Runtime (p. 343)": "string",
"Timeout (p. 343)": number,
"Version (p. 343)": "string",
"VpcConfig (p. 343)": {
"SecurityGroupIds (p. 345)": [ "string" ],
"SubnetIds (p. 345)": [ "string" ],
"VpcId (p. 345)": "string"
}
}
],
314
Response Elements
If the action is successful, the service sends back an HTTP 200 response.
The following data is returned in JSON format by the service.
Functions (p. 314)
A list of Lambda functions.
Type: array of FunctionConfiguration (p. 342) objects
NextMarker (p. 314)
A string, present if there are more functions.
Type: String
Errors
ServiceException
The AWS Lambda service encountered an internal error.
HTTP Status Code: 500
TooManyRequestsException
HTTP Status Code: 429
315
ListVersionsByFunction
List all versions of a function. For information about the versioning feature, see AWS Lambda Function
Versioning and Aliases.
Request Syntax
GET /2015-03-31/functions/FunctionName/versions?Marker=Marker&MaxItems=MaxItems
HTTP/1.1
Request Body
The request does not have a request body.
Response Syntax
HTTP/1.1 200
Content-type: application/json
{
"NextMarker (p. 317)": "string",
"Versions (p. 317)": [
{
"CodeSha256 (p. 342)": "string",
"CodeSize (p. 342)": number,
"Description (p. 342)": "string",
"FunctionArn (p. 342)": "string",
"FunctionName (p. 342)": "string",
"Handler (p. 342)": "string",
"LastModified (p. 342)": "string",
"MemorySize (p. 342)": number,
"Role (p. 342)": "string",
"Runtime (p. 343)": "string",
316
Response Elements
If the action is successful, the service sends back an HTTP 200 response.
The following data is returned in JSON format by the service.
NextMarker (p. 316)
A string, present if there are more function versions.
Type: String
Versions (p. 316)
A list of Lambda function versions.
Type: array of FunctionConfiguration (p. 342) objects
Errors
InvalidParameterValueException
One of the parameters in the request is invalid. For example, if you provided an IAM role for AWS
Lambda to assume in the CreateFunction or the UpdateFunctionConfiguration API, that
AWS Lambda is unable to assume you will get this exception.
HTTP Status Code: 400
ResourceNotFoundException
The resource (for example, a Lambda function or access policy statement) 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
HTTP Status Code: 429
317
PublishVersion
Publishes a version of your function from the current snapshot of $LATEST. That is, AWS Lambda takes
a snapshot of the function code and configuration information from $LATEST and publishes a new version.
The code and configuration cannot be modified after publication. For information about the versioning
feature, see AWS Lambda Function Versioning and Aliases.
Request Syntax
POST /2015-03-31/functions/FunctionName/versions HTTP/1.1
Content-type: application/json
{
"CodeSha256 (p. 318)": "string",
"Description (p. 318)": "string"
}
Request Body
The request requires the following data in JSON format.
CodeSha256 (p. 318)
The SHA256 hash of the deployment package you want to publish. This provides validation on the
code you are publishing. If you provide this parameter value must match the SHA256 of the $LATEST
version for the publication to succeed.
Type: String
Required: No
Description (p. 318)
The description for the version you are publishing. If not provided, AWS Lambda copies the description
from the $LATEST version.
Type: String
Length Constraints: Minimum length of 0. Maximum length of 256.
Required: No
Response Syntax
HTTP/1.1 201
Content-type: application/json
318
{
"CodeSha256 (p. 319)": "string",
"CodeSize (p. 319)": number,
"Description (p. 319)": "string",
"FunctionArn (p. 319)": "string",
"FunctionName (p. 319)": "string",
"Handler (p. 319)": "string",
"LastModified (p. 320)": "string",
"MemorySize (p. 320)": number,
"Role (p. 320)": "string",
"Runtime (p. 320)": "string",
"Timeout (p. 320)": number,
"Version (p. 320)": "string",
"VpcConfig (p. 320)": {
"SecurityGroupIds (p. 345)": [ "string" ],
"SubnetIds (p. 345)": [ "string" ],
"VpcId (p. 345)": "string"
}
}
Response Elements
If the action is successful, the service sends back an HTTP 201 response.
The following data is returned in JSON format by the service.
CodeSha256 (p. 318)
It is the SHA256 hash of your function deployment package.
Type: String
CodeSize (p. 318)
The size, in bytes, of the function .zip file you uploaded.
Type: Long
Description (p. 318)
The user-provided description.
Type: String
Length Constraints: Minimum length of 0. Maximum length of 256.
FunctionArn (p. 318)
The Amazon Resource Name (ARN) assigned to the function.
Type: String
Pattern:
arn:aws:lambda:[a-z]{2}-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_]+(:(\$LATEST|[a-zA-Z0-9-_]+))?
FunctionName (p. 318)
The name of the function.
Type: String
Length Constraints: Minimum length of 1. Maximum length of 140.
Pattern:
(arn:aws:lambda:)?([a-z]{2}-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?
Handler (p. 318)
The function Lambda calls to begin executing your function.
Type: String
Length Constraints: Maximum length of 128.
Pattern: [^\s]+
319
Errors
CodeStorageExceededException
You have exceeded your maximum total code size per account. Limits
HTTP Status Code: 400
InvalidParameterValueException
One of the parameters in the request is invalid. For example, if you provided an IAM role for AWS
Lambda to assume in the CreateFunction or the UpdateFunctionConfiguration API, that
AWS Lambda is unable to assume you will get this exception.
HTTP Status Code: 400
ResourceNotFoundException
The resource (for example, a Lambda function or access policy statement) specified in the request
does not exist.
HTTP Status Code: 404
ServiceException
The AWS Lambda service encountered an internal error.
HTTP Status Code: 500
320
TooManyRequestsException
HTTP Status Code: 429
321
RemovePermission
You can remove individual permissions from an resource policy associated with a Lambda function by
providing a statement ID that you provided when you added the permission.
If you are using versioning, the permissions you remove are specific to the Lambda function version or
alias you specify in the AddPermission request via the Qualifier parameter. For more information
about versioning, see AWS Lambda Function Versioning and Aliases.
Note that removal of a permission will cause an active event source to lose permission to the function.
You need permission for the lambda:RemovePermission action.
Request Syntax
DELETE /2015-03-31/functions/FunctionName/policy/StatementId?Qualifier=Qualifier
HTTP/1.1
Request Body
The request does not have a request body.
Response Syntax
HTTP/1.1 204
Response Elements
If the action is successful, the service sends back an HTTP 204 response with an empty HTTP body.
322
Errors
InvalidParameterValueException
One of the parameters in the request is invalid. For example, if you provided an IAM role for AWS
Lambda to assume in the CreateFunction or the UpdateFunctionConfiguration API, that
AWS Lambda is unable to assume you will get this exception.
HTTP Status Code: 400
ResourceNotFoundException
The resource (for example, a Lambda function or access policy statement) 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
HTTP Status Code: 429
323
UpdateAlias
Using this API you can update the function version to which the alias points and the alias description. For
more information, see Introduction to AWS Lambda Aliases.
This requires permission for the lambda:UpdateAlias action.
Request Syntax
PUT /2015-03-31/functions/FunctionName/aliases/Name HTTP/1.1
Content-type: application/json
{
"Description (p. 324)": "string",
"FunctionVersion (p. 324)": "string"
}
Request Body
The request requires the following data in JSON format.
Description (p. 324)
You can change the description of the alias using this parameter.
Type: String
Length Constraints: Minimum length of 0. Maximum length of 256.
Required: No
FunctionVersion (p. 324)
Using this parameter you can change the Lambda function version to which the alias points.
Type: String
Length Constraints: Minimum length of 1. Maximum length of 1024.
Pattern: (\$LATEST|[0-9]+)
Required: No
Response Syntax
HTTP/1.1 200
Content-type: application/json
324
{
"AliasArn (p. 325)": "string",
"Description (p. 325)": "string",
"FunctionVersion (p. 325)": "string",
"Name (p. 325)": "string"
}
Response Elements
If the action is successful, the service sends back an HTTP 200 response.
The following data is returned in JSON format by the service.
AliasArn (p. 324)
Lambda function ARN that is qualified using the alias name as the suffix. For example, if you create
an alias called BETA that points to a helloworld function version, the ARN is
arn:aws:lambda:aws-regions:acct-id:function:helloworld:BETA.
Type: String
Pattern:
arn:aws:lambda:[a-z]{2}-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_]+(:(\$LATEST|[a-zA-Z0-9-_]+))?
Description (p. 324)
Alias description.
Type: String
Length Constraints: Minimum length of 0. Maximum length of 256.
FunctionVersion (p. 324)
Function version to which the alias points.
Type: String
Length Constraints: Minimum length of 1. Maximum length of 1024.
Pattern: (\$LATEST|[0-9]+)
Name (p. 324)
Alias name.
Type: String
Length Constraints: Minimum length of 1. Maximum length of 128.
Pattern: (?!^[0-9]+$)([a-zA-Z0-9-_]+)
Errors
InvalidParameterValueException
One of the parameters in the request is invalid. For example, if you provided an IAM role for AWS
Lambda to assume in the CreateFunction or the UpdateFunctionConfiguration API, that
AWS Lambda is unable to assume you will get this exception.
HTTP Status Code: 400
ResourceNotFoundException
The resource (for example, a Lambda function or access policy statement) 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
HTTP Status Code: 429
325
UpdateEventSourceMapping
You can update an event source mapping. This is useful if you want to change the parameters of the
existing mapping without losing your position in the stream. You can change which function will receive
the stream records, but to change the stream itself, you must create a new mapping.
If you are using the versioning feature, you can update the event source mapping to map to a specific
Lambda function version or alias as described in the FunctionName parameter. For information about
the versioning feature, see AWS Lambda Function Versioning and Aliases.
If you disable the event source mapping, AWS Lambda stops polling. If you enable again, it will resume
polling from the time it had stopped polling, so you don't lose processing of any records. However, if you
delete event source mapping and create it again, it will reset.
This operation requires permission for the lambda:UpdateEventSourceMapping action.
Request Syntax
PUT /2015-03-31/event-source-mappings/UUID HTTP/1.1
Content-type: application/json
{
"BatchSize (p. 326)": number,
"Enabled (p. 326)": boolean,
"FunctionName (p. 326)": "string"
}
Request Body
The request requires the following data in JSON format.
BatchSize (p. 326)
The maximum number of stream records that can be sent to your Lambda function for a single
invocation.
Type: Integer
Valid Range: Minimum value of 1. Maximum value of 10000.
Required: No
Enabled (p. 326)
Specifies whether AWS Lambda should actively poll the stream or not. If disabled, AWS Lambda will
not poll the stream.
Type: Boolean
Required: No
FunctionName (p. 326)
The Lambda function to which you want the stream records sent.
You can specify a function name (for example, Thumbnail) or you can specify Amazon Resource
Name (ARN) of the function (for example,
arn:aws:lambda:us-west-2:account-id:function:ThumbNail). AWS Lambda also allows
you to specify a partial ARN (for example, account-id:Thumbnail).
326
If you are using versioning, you can also provide a qualified function ARN (ARN that is qualified with
function version or alias name as suffix). For more information about versioning, see AWS Lambda
Function Versioning and Aliases
Note that the length constraint applies only to the ARN. If you specify only the function name, it is
limited to 64 character in length.
Type: String
Length Constraints: Minimum length of 1. Maximum length of 140.
Pattern:
(arn:aws:lambda:)?([a-z]{2}-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?
Required: No
Response Syntax
HTTP/1.1 202
Content-type: application/json
{
"BatchSize (p. 327)": number,
"EventSourceArn (p. 327)": "string",
"FunctionArn (p. 327)": "string",
"LastModified (p. 327)": number,
"LastProcessingResult (p. 327)": "string",
"State (p. 328)": "string",
"StateTransitionReason (p. 328)": "string",
"UUID (p. 328)": "string"
}
Response Elements
If the action is successful, the service sends back an HTTP 202 response.
The following data is returned in JSON format by the service.
BatchSize (p. 327)
The largest number of records that AWS Lambda will retrieve from your event source at the time of
invoking your function. Your function receives an event with all the retrieved records.
Type: Integer
Valid Range: Minimum value of 1. Maximum value of 10000.
EventSourceArn (p. 327)
The Amazon Resource Name (ARN) of the Amazon Kinesis stream that is the source of events.
Type: String
Pattern: arn:aws:([a-zA-Z0-9\-])+:([a-z]{2}-[a-z]+-\d{1})?:(\d{12})?:(.*)
FunctionArn (p. 327)
The Lambda function to invoke when AWS Lambda detects an event on the stream.
Type: String
Pattern:
arn:aws:lambda:[a-z]{2}-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_]+(:(\$LATEST|[a-zA-Z0-9-_]+))?
LastModified (p. 327)
The UTC time string indicating the last time the event mapping was updated.
Type: Timestamp
LastProcessingResult (p. 327)
The result of the last AWS Lambda invocation of your Lambda function.
327
Type: String
State (p. 327)
The state of the event source mapping. It can be Creating, Enabled, Disabled, Enabling,
Disabling, Updating, or Deleting.
Type: String
StateTransitionReason (p. 327)
The reason the event source mapping is in its current state. It is either user-requested or an AWS
Lambda-initiated state transition.
Type: String
UUID (p. 327)
The AWS Lambda assigned opaque identifier for the mapping.
Type: String
Errors
InvalidParameterValueException
One of the parameters in the request is invalid. For example, if you provided an IAM role for AWS
Lambda to assume in the CreateFunction or the UpdateFunctionConfiguration API, that
AWS Lambda is unable to assume you will get this exception.
HTTP Status Code: 400
ResourceConflictException
The resource already exists.
HTTP Status Code: 409
ResourceNotFoundException
The resource (for example, a Lambda function or access policy statement) 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
HTTP Status Code: 429
328
UpdateFunctionCode
Updates the code for the specified Lambda function. This operation must only be used on an existing
Lambda function and cannot be used to update the function configuration.
If you are using the versioning feature, note this API will always update the $LATEST version of your
Lambda function. For information about the versioning feature, see AWS Lambda Function Versioning
and Aliases.
This operation requires permission for the lambda:UpdateFunctionCode action.
Request Syntax
PUT /2015-03-31/functions/FunctionName/code HTTP/1.1
Content-type: application/json
{
"Publish (p. 329)": boolean,
"S3Bucket (p. 329)": "string",
"S3Key (p. 330)": "string",
"S3ObjectVersion (p. 330)": "string",
"ZipFile (p. 330)": blob
}
Request Body
The request requires the following data in JSON format.
Publish (p. 329)
This boolean parameter can be used to request AWS Lambda to update the Lambda function and
publish a version as an atomic operation.
Type: Boolean
Required: No
S3Bucket (p. 329)
Amazon S3 bucket name where the .zip file containing your deployment package is stored. This
bucket must reside in the same AWS region where you are creating the Lambda function.
Type: String
Length Constraints: Minimum length of 3. Maximum length of 63.
Pattern: ^[0-9A-Za-z\.\-_]*(?<!\.)$
Required: No
329
Response Syntax
HTTP/1.1 200
Content-type: application/json
{
"CodeSha256 (p. 330)": "string",
"CodeSize (p. 330)": number,
"Description (p. 331)": "string",
"FunctionArn (p. 331)": "string",
"FunctionName (p. 331)": "string",
"Handler (p. 331)": "string",
"LastModified (p. 331)": "string",
"MemorySize (p. 331)": number,
"Role (p. 331)": "string",
"Runtime (p. 331)": "string",
"Timeout (p. 331)": number,
"Version (p. 331)": "string",
"VpcConfig (p. 332)": {
"SecurityGroupIds (p. 345)": [ "string" ],
"SubnetIds (p. 345)": [ "string" ],
"VpcId (p. 345)": "string"
}
}
Response Elements
If the action is successful, the service sends back an HTTP 200 response.
The following data is returned in JSON format by the service.
CodeSha256 (p. 330)
It is the SHA256 hash of your function deployment package.
Type: String
CodeSize (p. 330)
The size, in bytes, of the function .zip file you uploaded.
330
Type: Long
Description (p. 330)
The user-provided description.
Type: String
Length Constraints: Minimum length of 0. Maximum length of 256.
FunctionArn (p. 330)
The Amazon Resource Name (ARN) assigned to the function.
Type: String
Pattern:
arn:aws:lambda:[a-z]{2}-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_]+(:(\$LATEST|[a-zA-Z0-9-_]+))?
FunctionName (p. 330)
The name of the function.
Type: String
Length Constraints: Minimum length of 1. Maximum length of 140.
Pattern:
(arn:aws:lambda:)?([a-z]{2}-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?
Handler (p. 330)
The function Lambda calls to begin executing your function.
Type: String
Length Constraints: Maximum length of 128.
Pattern: [^\s]+
LastModified (p. 330)
The time stamp of the last time you updated the function.
Type: String
MemorySize (p. 330)
The memory size, in MB, you configured for the function. Must be a multiple of 64 MB.
Type: Integer
Valid Range: Minimum value of 128. Maximum value of 1536.
Role (p. 330)
The Amazon Resource Name (ARN) of the IAM role that Lambda assumes when it executes your
function to access any other Amazon Web Services (AWS) resources.
Type: String
Pattern: arn:aws:iam::\d{12}:role/?[a-zA-Z_0-9+=,.@\-_/]+
Runtime (p. 330)
The runtime environment for the Lambda function.
To use the Node.js runtime v4.3, set the value to "nodejs4.3". To use earlier runtime (v0.10.42), set
the value to "nodejs".
Type: String
Valid Values: nodejs | nodejs4.3 | java8 | python2.7
Timeout (p. 330)
The function execution time at which Lambda should terminate the function. Because the execution
time has cost implications, we recommend you set this value based on your expected execution time.
The default is 3 seconds.
Type: Integer
Valid Range: Minimum value of 1.
Version (p. 330)
The version of the Lambda function.
Type: String
Length Constraints: Minimum length of 1. Maximum length of 1024.
Pattern: (\$LATEST|[0-9]+)
331
Errors
CodeStorageExceededException
You have exceeded your maximum total code size per account. Limits
HTTP Status Code: 400
InvalidParameterValueException
One of the parameters in the request is invalid. For example, if you provided an IAM role for AWS
Lambda to assume in the CreateFunction or the UpdateFunctionConfiguration API, that
AWS Lambda is unable to assume you will get this exception.
HTTP Status Code: 400
ResourceNotFoundException
The resource (for example, a Lambda function or access policy statement) 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
HTTP Status Code: 429
332
UpdateFunctionConfiguration
Updates the configuration parameters for the specified Lambda function by using the values provided in
the request. You provide only the parameters you want to change. This operation must only be used on
an existing Lambda function and cannot be used to update the function's code.
If you are using the versioning feature, note this API will always update the $LATEST version of your
Lambda function. For information about the versioning feature, see AWS Lambda Function Versioning
and Aliases.
This operation requires permission for the lambda:UpdateFunctionConfiguration action.
Request Syntax
PUT /2015-03-31/functions/FunctionName/configuration HTTP/1.1
Content-type: application/json
{
"Description (p. 333)": "string",
"Handler (p. 334)": "string",
"MemorySize (p. 334)": number,
"Role (p. 334)": "string",
"Runtime (p. 334)": "string",
"Timeout (p. 334)": number,
"VpcConfig (p. 334)": {
"SecurityGroupIds (p. 344)": [ "string" ],
"SubnetIds (p. 344)": [ "string" ]
}
}
Request Body
The request requires the following data in JSON format.
Description (p. 333)
A short user-defined function description. AWS Lambda does not use this value. Assign a meaningful
description as you see fit.
Type: String
Length Constraints: Minimum length of 0. Maximum length of 256.
Required: No
333
Response Syntax
HTTP/1.1 200
Content-type: application/json
{
"CodeSha256 (p. 335)": "string",
334
Response Elements
If the action is successful, the service sends back an HTTP 200 response.
The following data is returned in JSON format by the service.
CodeSha256 (p. 334)
It is the SHA256 hash of your function deployment package.
Type: String
CodeSize (p. 334)
The size, in bytes, of the function .zip file you uploaded.
Type: Long
Description (p. 334)
The user-provided description.
Type: String
Length Constraints: Minimum length of 0. Maximum length of 256.
FunctionArn (p. 334)
The Amazon Resource Name (ARN) assigned to the function.
Type: String
Pattern:
arn:aws:lambda:[a-z]{2}-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_]+(:(\$LATEST|[a-zA-Z0-9-_]+))?
FunctionName (p. 334)
The name of the function.
Type: String
Length Constraints: Minimum length of 1. Maximum length of 140.
Pattern:
(arn:aws:lambda:)?([a-z]{2}-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?
Handler (p. 334)
The function Lambda calls to begin executing your function.
Type: String
Length Constraints: Maximum length of 128.
Pattern: [^\s]+
LastModified (p. 334)
The time stamp of the last time you updated the function.
Type: String
335
Errors
InvalidParameterValueException
One of the parameters in the request is invalid. For example, if you provided an IAM role for AWS
Lambda to assume in the CreateFunction or the UpdateFunctionConfiguration API, that
AWS Lambda is unable to assume you will get this exception.
HTTP Status Code: 400
ResourceNotFoundException
The resource (for example, a Lambda function or access policy statement) 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
HTTP Status Code: 429
336
Data Types
The following data types are supported:
AliasConfiguration (p. 338)
EventSourceMappingConfiguration (p. 339)
FunctionCode (p. 340)
FunctionCodeLocation (p. 341)
FunctionConfiguration (p. 342)
VpcConfig (p. 344)
VpcConfigResponse (p. 345)
337
AliasConfiguration
Provides configuration information about a Lambda function version alias.
Contents
AliasArn
Lambda function ARN that is qualified using the alias name as the suffix. For example, if you create
an alias called BETA that points to a helloworld function version, the ARN is
arn:aws:lambda:aws-regions:acct-id:function:helloworld:BETA.
Type: String
Pattern:
arn:aws:lambda:[a-z]{2}-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_]+(:(\$LATEST|[a-zA-Z0-9-_]+))?
Required: No
Description
Alias description.
Type: String
Length Constraints: Minimum length of 0. Maximum length of 256.
Required: No
FunctionVersion
Function version to which the alias points.
Type: String
Length Constraints: Minimum length of 1. Maximum length of 1024.
Pattern: (\$LATEST|[0-9]+)
Required: No
Name
Alias name.
Type: String
Length Constraints: Minimum length of 1. Maximum length of 128.
Pattern: (?!^[0-9]+$)([a-zA-Z0-9-_]+)
Required: No
338
EventSourceMappingConfiguration
Describes mapping between an Amazon Kinesis stream and a Lambda function.
Contents
BatchSize
The largest number of records that AWS Lambda will retrieve from your event source at the time of
invoking your function. Your function receives an event with all the retrieved records.
Type: Integer
Valid Range: Minimum value of 1. Maximum value of 10000.
Required: No
EventSourceArn
The Amazon Resource Name (ARN) of the Amazon Kinesis stream that is the source of events.
Type: String
Pattern: arn:aws:([a-zA-Z0-9\-])+:([a-z]{2}-[a-z]+-\d{1})?:(\d{12})?:(.*)
Required: No
FunctionArn
The Lambda function to invoke when AWS Lambda detects an event on the stream.
Type: String
Pattern:
arn:aws:lambda:[a-z]{2}-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_]+(:(\$LATEST|[a-zA-Z0-9-_]+))?
Required: No
LastModified
The UTC time string indicating the last time the event mapping was updated.
Type: Timestamp
Required: No
LastProcessingResult
The result of the last AWS Lambda invocation of your Lambda function.
Type: String
Required: No
State
The state of the event source mapping. It can be Creating, Enabled, Disabled, Enabling,
Disabling, Updating, or Deleting.
Type: String
Required: No
StateTransitionReason
The reason the event source mapping is in its current state. It is either user-requested or an AWS
Lambda-initiated state transition.
Type: String
Required: No
UUID
The AWS Lambda assigned opaque identifier for the mapping.
Type: String
Required: No
339
FunctionCode
The code for the Lambda function.
Contents
S3Bucket
Amazon S3 bucket name where the .zip file containing your deployment package is stored. This
bucket must reside in the same AWS region where you are creating the Lambda function.
Type: String
Length Constraints: Minimum length of 3. Maximum length of 63.
Pattern: ^[0-9A-Za-z\.\-_]*(?<!\.)$
Required: No
S3Key
The Amazon S3 object (the deployment package) key name you want to upload.
Type: String
Length Constraints: Minimum length of 1. Maximum length of 1024.
Required: No
S3ObjectVersion
The Amazon S3 object (the deployment package) version you want to upload.
Type: String
Length Constraints: Minimum length of 1. Maximum length of 1024.
Required: No
ZipFile
The contents of your zip file containing your deployment package. If you are using the web API
directly, the contents of the zip file must be base64-encoded. If you are using the AWS SDKs or the
AWS CLI, the SDKs or CLI will do the encoding for you. For more information about creating a .zip
file, go to Execution Permissions in the AWS Lambda Developer Guide.
Type: Base64-encoded binary data
Required: No
340
FunctionCodeLocation
The object for the Lambda function location.
Contents
Location
The presigned URL you can use to download the function's .zip file that you previously uploaded.
The URL is valid for up to 10 minutes.
Type: String
Required: No
RepositoryType
The repository from which you can download the function.
Type: String
Required: No
341
FunctionConfiguration
A complex type that describes function metadata.
Contents
CodeSha256
It is the SHA256 hash of your function deployment package.
Type: String
Required: No
CodeSize
The size, in bytes, of the function .zip file you uploaded.
Type: Long
Required: No
Description
The user-provided description.
Type: String
Length Constraints: Minimum length of 0. Maximum length of 256.
Required: No
FunctionArn
The Amazon Resource Name (ARN) assigned to the function.
Type: String
Pattern:
arn:aws:lambda:[a-z]{2}-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_]+(:(\$LATEST|[a-zA-Z0-9-_]+))?
Required: No
FunctionName
The name of the function.
Type: String
Length Constraints: Minimum length of 1. Maximum length of 140.
Pattern:
(arn:aws:lambda:)?([a-z]{2}-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?
Required: No
Handler
The function Lambda calls to begin executing your function.
Type: String
Length Constraints: Maximum length of 128.
Pattern: [^\s]+
Required: No
LastModified
The time stamp of the last time you updated the function.
Type: String
Required: No
MemorySize
The memory size, in MB, you configured for the function. Must be a multiple of 64 MB.
Type: Integer
Valid Range: Minimum value of 128. Maximum value of 1536.
Required: No
Role
The Amazon Resource Name (ARN) of the IAM role that Lambda assumes when it executes your
function to access any other Amazon Web Services (AWS) resources.
342
Type: String
Pattern: arn:aws:iam::\d{12}:role/?[a-zA-Z_0-9+=,.@\-_/]+
Required: No
Runtime
The runtime environment for the Lambda function.
To use the Node.js runtime v4.3, set the value to "nodejs4.3". To use earlier runtime (v0.10.42), set
the value to "nodejs".
Type: String
Valid Values: nodejs | nodejs4.3 | java8 | python2.7
Required: No
Timeout
The function execution time at which Lambda should terminate the function. Because the execution
time has cost implications, we recommend you set this value based on your expected execution time.
The default is 3 seconds.
Type: Integer
Valid Range: Minimum value of 1.
Required: No
Version
The version of the Lambda function.
Type: String
Length Constraints: Minimum length of 1. Maximum length of 1024.
Pattern: (\$LATEST|[0-9]+)
Required: No
VpcConfig
VPC configuration associated with your Lambda function.
Type: VpcConfigResponse (p. 345) object
Required: No
343
VpcConfig
If your Lambda function accesses resources in a VPC, you provide this parameter identifying the list of
security group IDs and subnet IDs. These must belong to the same VPC. You must provide at least one
security group and one subnet ID.
Contents
SecurityGroupIds
A list of one or more security groups IDs in your VPC.
Type: array of Strings
Array Members: Maximum number of 5 items.
Required: No
SubnetIds
A list of one or more subnet IDs in your VPC.
Type: array of Strings
Array Members: Maximum number of 16 items.
Required: No
344
VpcConfigResponse
VPC configuration associated with your Lambda function.
Contents
SecurityGroupIds
A list of security group IDs associated with the Lambda function.
Type: array of Strings
Array Members: Maximum number of 5 items.
Required: No
SubnetIds
A list of subnet IDs associated with the Lambda function.
Type: array of Strings
Array Members: Maximum number of 16 items.
Required: No
VpcId
The VPC ID associated with you Lambda function.
Type: String
Required: No
345
Document History
The following table describes the important changes to the AWS Lambda Developer Guide.
Change
Description
Date
Asia Pacific (Seoul) Re- AWS Lambda is now available in the Asia Pacific (Seoul) Re- In this region
gion. For more information about Lambda regions and endlease
points, see Regions and Endpoints in the AWS General Reference.
Asia Pacific (Sydney)
Region
June 23,
2016
The Lambda console has been updated to simplify the rolecreation process. For more information, see Step 2.1: Create
a Hello World Lambda Function (p. 39).
June 23,
2016
AWS Lambda now sup- AWS Lambda added support for Node.js runtime v4.3. For more April 07,
ports Node.js runtime
information, see Programming Model (Node.js) (p. 51).
2016
v4.3
EU (Frankfurt) region
Lambda is now available in the EU (Frankfurt) region. For more March 14,
information about Lambda regions and endpoints, see Regions 2016
and Endpoints in the AWS General Reference.
VPC support
346
Change
Description
Date
Content reorganization
December
9, 2015
AWS Lambda runtime has been updated with the following SDK November
and Linux kernel versions in this release:
4, 2015
AWS SDK for JavaScript: 2.2.12
Boto SDK: 1.2.1
Linux kernel version: 3.14.48-33.39.amzn1.x86_6.
For more information, see Lambda Execution Environment and
Available Libraries (p. 33).
Versioning support, Py- AWS Lambda introduces the following features in this release. October 08,
thon for developing code
2015
Python: You can now develop your Lambda function code
for Lambda functions,
using Python. For more information, see Programming Modscheduled events, and
el (p. 51).
increase in execution
time
Versioning: You can maintain one or more versions of your
Lambda function. Versioning allows you to control which
Lambda function version is executed in different environments
(for example, development, testing, or production). For more
information, see AWS Lambda Function Versioning and Aliases (p. 101).
Scheduled events: You can also set up AWS Lambda to invoke your code on a regular, scheduled basis using the AWS
Lambda console. You can specify a fixed rate (number of
hours, days, or weeks) or you can specify a cron expression.
For an example, see Using AWS Lambda with Scheduled
Events (p. 207).
Increase in execution time: You can now set up your Lambda
functions to run for up to five minutes allowing longer running
functions such as large volume data ingestion and processing
jobs.
347
Change
Description
Date
The following new walkthroughs are added. They both use Java August 27,
Lambda function.
2015
Tutorial: Using AWS Lambda with Amazon DynamoDB (p. 152)
Using AWS Lambda as Mobile Application Backend (Custom
Event Source: Android) (p. 194)
Until now, to invoke your Lambda function from your web, mo- July 09,
bile, or IoT application you needed the AWS SDKs (for example, 2015
AWS SDK for Java, AWS SDK for Android, or AWS SDK for
iOS). Now, AWS Lambda supports invoking a Lambda function
with REST-compatible clients through a customized API that
you can create using Amazon API Gateway. You can send requests to your Lambda function endpoint URL. You can configure security on the endpoint to allow open access, leverage
AWS Identity and Access Management (IAM) to authorize access, or use API keys to meter access to your Lambda functions
by others.
For an example Getting Started exercise, see Using AWS
Lambda with Amazon API Gateway (On-Demand Over HTTPS) (p. 181).
For more information about the Amazon API Gateway, see http://
aws.amazon.com/api-gateway/.
AWS Lambda console provides a set of blueprints. Each blue- In this reprint provides a sample event source configuration and sample lease
code for your Lambda function that you can use to easily create
Lambda-based applications. All of the AWS Lambda Getting
Started exercises now use the blueprints. For more information,
see Getting Started (p. 35).
AWS Lambda now sup- You can now author Lambda code in Java. For more informaports Java to author
tion, see Programming Model (p. 51).
your Lambda functions.
June 15,
2015
May 28,
2015
348
Change
Description
Date
AWS Lambda now generally available with added support for mobile
backends
Preview release
349
November
13, 2014
AWS Glossary
For the latest AWS terminology, see the AWS Glossary in the AWS General Reference.
350