README.md
  1  # AWS Lambda Construct Library
  2  <!--BEGIN STABILITY BANNER-->
  3  
  4  ---
  5  
  6  ![cfn-resources: Stable](https://img.shields.io/badge/cfn--resources-stable-success.svg?style=for-the-badge)
  7  
  8  ![cdk-constructs: Stable](https://img.shields.io/badge/cdk--constructs-stable-success.svg?style=for-the-badge)
  9  
 10  ---
 11  
 12  <!--END STABILITY BANNER-->
 13  
 14  This construct library allows you to define AWS Lambda Functions.
 15  
 16  ```ts
 17  const fn = new lambda.Function(this, 'MyFunction', {
 18    runtime: lambda.Runtime.NODEJS_12_X,
 19    handler: 'index.handler',
 20    code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler')),
 21  });
 22  ```
 23  
 24  ## Handler Code
 25  
 26  The `lambda.Code` class includes static convenience methods for various types of
 27  runtime code.
 28  
 29   * `lambda.Code.fromBucket(bucket, key[, objectVersion])` - specify an S3 object
 30     that contains the archive of your runtime code.
 31   * `lambda.Code.fromInline(code)` - inline the handle code as a string. This is
 32     limited to supported runtimes and the code cannot exceed 4KiB.
 33   * `lambda.Code.fromAsset(path)` - specify a directory or a .zip file in the local
 34     filesystem which will be zipped and uploaded to S3 before deployment. See also
 35     [bundling asset code](#bundling-asset-code).
 36   * `lambda.Code.fromDockerBuild(path, options)` - use the result of a Docker
 37     build as code. The runtime code is expected to be located at `/asset` in the
 38     image and will be zipped and uploaded to S3 as an asset.
 39  
 40  The following example shows how to define a Python function and deploy the code
 41  from the local directory `my-lambda-handler` to it:
 42  
 43  [Example of Lambda Code from Local Assets](test/integ.assets.lit.ts)
 44  
 45  When deploying a stack that contains this code, the directory will be zip
 46  archived and then uploaded to an S3 bucket, then the exact location of the S3
 47  objects will be passed when the stack is deployed.
 48  
 49  During synthesis, the CDK expects to find a directory on disk at the asset
 50  directory specified. Note that we are referencing the asset directory relatively
 51  to our CDK project directory. This is especially important when we want to share
 52  this construct through a library. Different programming languages will have
 53  different techniques for bundling resources into libraries.
 54  
 55  ## Docker Images
 56  
 57  Lambda functions allow specifying their handlers within docker images. The docker
 58  image can be an image from ECR or a local asset that the CDK will package and load
 59  into ECR.
 60  
 61  The following `DockerImageFunction` construct uses a local folder with a
 62  Dockerfile as the asset that will be used as the function handler.
 63  
 64  ```ts
 65  new lambda.DockerImageFunction(this, 'AssetFunction', {
 66    code: lambda.DockerImageCode.fromImageAsset(path.join(__dirname, 'docker-handler')),
 67  });
 68  ```
 69  
 70  You can also specify an image that already exists in ECR as the function handler.
 71  
 72  ```ts
 73  import * as ecr from '@aws-cdk/aws-ecr';
 74  const repo = new ecr.Repository(this, 'Repository');
 75  
 76  new lambda.DockerImageFunction(this, 'ECRFunction', {
 77    code: lambda.DockerImageCode.fromEcr(repo),
 78  });
 79  ```
 80  
 81  The props for these docker image resources allow overriding the image's `CMD`, `ENTRYPOINT`, and `WORKDIR`
 82  configurations. See their docs for more information.
 83  
 84  ## Execution Role
 85  
 86  Lambda functions assume an IAM role during execution. In CDK by default, Lambda
 87  functions will use an autogenerated Role if one is not provided.
 88  
 89  The autogenerated Role is automatically given permissions to execute the Lambda
 90  function. To reference the autogenerated Role:
 91  
 92  ```ts
 93  const fn = new lambda.Function(this, 'MyFunction', {
 94    runtime: lambda.Runtime.NODEJS_12_X,
 95    handler: 'index.handler',
 96    code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler')),
 97  });
 98  
 99  const role = fn.role; // the Role
100  ```
101  
102  You can also provide your own IAM role. Provided IAM roles will not automatically
103  be given permissions to execute the Lambda function. To provide a role and grant
104  it appropriate permissions:
105  
106  ```ts
107  const myRole = new iam.Role(this, 'My Role', {
108    assumedBy: new iam.ServicePrincipal('sns.amazonaws.com'),
109  });
110  
111  const fn = new lambda.Function(this, 'MyFunction', {
112    runtime: lambda.Runtime.NODEJS_12_X,
113    handler: 'index.handler',
114    code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler')),
115    role: myRole, // user-provided role
116  });
117  
118  myRole.addManagedPolicy(iam.ManagedPolicy.fromAwsManagedPolicyName("service-role/AWSLambdaBasicExecutionRole"));
119  myRole.addManagedPolicy(iam.ManagedPolicy.fromAwsManagedPolicyName("service-role/AWSLambdaVPCAccessExecutionRole")); // only required if your function lives in a VPC
120  ```
121  
122  ## Resource-based Policies
123  
124  AWS Lambda supports resource-based policies for controlling access to Lambda
125  functions and layers on a per-resource basis. In particular, this allows you to
126  give permission to AWS services and other AWS accounts to modify and invoke your
127  functions. You can also restrict permissions given to AWS services by providing
128  a source account or ARN (representing the account and identifier of the resource
129  that accesses the function or layer).
130  
131  ```ts
132  declare const fn: lambda.Function;
133  const principal = new iam.ServicePrincipal('my-service');
134  
135  fn.grantInvoke(principal);
136  
137  // Equivalent to:
138  fn.addPermission('my-service Invocation', {
139    principal: principal,
140  });
141  ```
142  
143  For more information, see [Resource-based
144  policies](https://docs.aws.amazon.com/lambda/latest/dg/access-control-resource-based.html)
145  in the AWS Lambda Developer Guide.
146  
147  Providing an unowned principal (such as account principals, generic ARN
148  principals, service principals, and principals in other accounts) to a call to
149  `fn.grantInvoke` will result in a resource-based policy being created. If the
150  principal in question has conditions limiting the source account or ARN of the
151  operation (see above), these conditions will be automatically added to the
152  resource policy.
153  
154  ```ts
155  declare const fn: lambda.Function;
156  const servicePrincipal = new iam.ServicePrincipal('my-service');
157  const sourceArn = 'arn:aws:s3:::my-bucket';
158  const sourceAccount = '111122223333';
159  const servicePrincipalWithConditions = servicePrincipal.withConditions({
160    ArnLike: {
161      'aws:SourceArn': sourceArn,
162    },
163    StringEquals: {
164      'aws:SourceAccount': sourceAccount,
165    },
166  });
167  
168  fn.grantInvoke(servicePrincipalWithConditions);
169  
170  // Equivalent to:
171  fn.addPermission('my-service Invocation', {
172    principal: servicePrincipal,
173    sourceArn: sourceArn,
174    sourceAccount: sourceAccount,
175  });
176  ```
177  
178  ## Versions
179  
180  You can use
181  [versions](https://docs.aws.amazon.com/lambda/latest/dg/configuration-versions.html)
182  to manage the deployment of your AWS Lambda functions. For example, you can
183  publish a new version of a function for beta testing without affecting users of
184  the stable production version.
185  
186  The function version includes the following information:
187  
188  * The function code and all associated dependencies.
189  * The Lambda runtime that executes the function.
190  * All of the function settings, including the environment variables.
191  * A unique Amazon Resource Name (ARN) to identify this version of the function.
192  
193  You could create a version to your lambda function using the `Version` construct.
194  
195  ```ts
196  declare const fn: lambda.Function;
197  const version = new lambda.Version(this, 'MyVersion', {
198    lambda: fn,
199  });
200  ```
201  
202  The major caveat to know here is that a function version must always point to a
203  specific 'version' of the function. When the function is modified, the version
204  will continue to point to the 'then version' of the function.
205  
206  One way to ensure that the `lambda.Version` always points to the latest version
207  of your `lambda.Function` is to set an environment variable which changes at
208  least as often as your code does. This makes sure the function always has the
209  latest code. For instance -
210  
211  ```ts
212  const codeVersion = "stringOrMethodToGetCodeVersion";
213  const fn = new lambda.Function(this, 'MyFunction', {
214    runtime: lambda.Runtime.NODEJS_12_X,
215    handler: 'index.handler',
216    code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler')),
217    environment: {
218      'CodeVersionString': codeVersion,
219    },
220  });
221  ```
222  
223  The `fn.latestVersion` property returns a `lambda.IVersion` which represents
224  the `$LATEST` pseudo-version.
225  
226  However, most AWS services require a specific AWS Lambda version,
227  and won't allow you to use `$LATEST`. Therefore, you would normally want
228  to use `lambda.currentVersion`.
229  
230  The `fn.currentVersion` property can be used to obtain a `lambda.Version`
231  resource that represents the AWS Lambda function defined in your application.
232  Any change to your function's code or configuration will result in the creation
233  of a new version resource. You can specify options for this version through the
234  `currentVersionOptions` property.
235  
236  NOTE: The `currentVersion` property is only supported when your AWS Lambda function
237  uses either `lambda.Code.fromAsset` or `lambda.Code.fromInline`. Other types
238  of code providers (such as `lambda.Code.fromBucket`) require that you define a
239  `lambda.Version` resource directly since the CDK is unable to determine if
240  their contents had changed.
241  
242  ### `currentVersion`: Updated hashing logic
243  
244  To produce a new lambda version each time the lambda function is modified, the
245  `currentVersion` property under the hood, computes a new logical id based on the
246  properties of the function. This informs CloudFormation that a new
247  `AWS::Lambda::Version` resource should be created pointing to the updated Lambda
248  function.
249  
250  However, a bug was introduced in this calculation that caused the logical id to
251  change when it was not required (ex: when the Function's `Tags` property, or
252  when the `DependsOn` clause was modified). This caused the deployment to fail
253  since the Lambda service does not allow creating duplicate versions.
254  
255  This has been fixed in the AWS CDK but *existing* users need to opt-in via a
256  [feature flag]. Users who have run `cdk init` since this fix will be opted in,
257  by default.
258  
259  Existing users will need to enable the [feature flag]
260  `@aws-cdk/aws-lambda:recognizeVersionProps`. Since CloudFormation does not
261  allow duplicate versions, they will also need to make some modification to
262  their function so that a new version can be created. Any trivial change such as
263  a whitespace change in the code or a no-op environment variable will suffice.
264  
265  When the new logic is in effect, you may rarely come across the following error:
266  `The following properties are not recognized as version properties`. This will
267  occur, typically when [property overrides] are used, when a new property
268  introduced in `AWS::Lambda::Function` is used that CDK is still unaware of.
269  
270  To overcome this error, use the API `Function.classifyVersionProperty()` to
271  record whether a new version should be generated when this property is changed.
272  This can be typically determined by checking whether the property can be
273  modified using the *[UpdateFunctionConfiguration]* API or not.
274  
275  [feature flag]: https://docs.aws.amazon.com/cdk/latest/guide/featureflags.html
276  [property overrides]: https://docs.aws.amazon.com/cdk/latest/guide/cfn_layer.html#cfn_layer_raw
277  [UpdateFunctionConfiguration]: https://docs.aws.amazon.com/lambda/latest/dg/API_UpdateFunctionConfiguration.html
278  
279  ## Aliases
280  
281  You can define one or more
282  [aliases](https://docs.aws.amazon.com/lambda/latest/dg/configuration-aliases.html)
283  for your AWS Lambda function. A Lambda alias is like a pointer to a specific
284  Lambda function version. Users can access the function version using the alias
285  ARN.
286  
287  The `version.addAlias()` method can be used to define an AWS Lambda alias that
288  points to a specific version.
289  
290  The following example defines an alias named `live` which will always point to a
291  version that represents the function as defined in your CDK app. When you change
292  your lambda code or configuration, a new resource will be created. You can
293  specify options for the current version through the `currentVersionOptions`
294  property.
295  
296  ```ts
297  const fn = new lambda.Function(this, 'MyFunction', {
298    currentVersionOptions: {
299      removalPolicy: RemovalPolicy.RETAIN, // retain old versions
300      retryAttempts: 1,                   // async retry attempts
301    },
302    runtime: lambda.Runtime.NODEJS_12_X,
303    handler: 'index.handler',
304    code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler')),
305  });
306  
307  fn.currentVersion.addAlias('live');
308  ```
309  
310  ## Layers
311  
312  The `lambda.LayerVersion` class can be used to define Lambda layers and manage
313  granting permissions to other AWS accounts or organizations.
314  
315  [Example of Lambda Layer usage](test/integ.layer-version.lit.ts)
316  
317  By default, updating a layer creates a new layer version, and CloudFormation will delete the old version as part of the stack update.
318  
319  Alternatively, a removal policy can be used to retain the old version:
320  
321  ```ts
322  new lambda.LayerVersion(this, 'MyLayer', {
323    removalPolicy: RemovalPolicy.RETAIN,
324    code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler')),
325  });
326  ```
327  
328  ## Architecture
329  
330  Lambda functions, by default, run on compute systems that have the 64 bit x86 architecture.
331  
332  The AWS Lambda service also runs compute on the ARM architecture, which can reduce cost
333  for some workloads.
334  
335  A lambda function can be configured to be run on one of these platforms:
336  
337  ```ts
338  new lambda.Function(this, 'MyFunction', {
339    runtime: lambda.Runtime.NODEJS_12_X,
340    handler: 'index.handler',
341    code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler')),
342    architecture: lambda.Architecture.ARM_64,
343  });
344  ```
345  
346  Similarly, lambda layer versions can also be tagged with architectures it is compatible with.
347  
348  ```ts
349  new lambda.LayerVersion(this, 'MyLayer', {
350    removalPolicy: RemovalPolicy.RETAIN,
351    code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler')),
352    compatibleArchitectures: [lambda.Architecture.X86_64, lambda.Architecture.ARM_64],
353  });
354  ```
355  
356  ## Lambda Insights
357  
358  Lambda functions can be configured to use CloudWatch [Lambda Insights](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Lambda-Insights.html)
359  which provides low-level runtime metrics for a Lambda functions.
360  
361  ```ts
362  new lambda.Function(this, 'MyFunction', {
363    runtime: lambda.Runtime.NODEJS_12_X,
364    handler: 'index.handler',
365    code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler')),
366    insightsVersion: lambda.LambdaInsightsVersion.VERSION_1_0_98_0,
367  });
368  ```
369  
370  If the version of insights is not yet available in the CDK, you can also provide the ARN directly as so -
371  
372  ```ts
373  const layerArn = 'arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension:14';
374  new lambda.Function(this, 'MyFunction', {
375    runtime: lambda.Runtime.NODEJS_12_X,
376    handler: 'index.handler',
377    code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler')),
378    insightsVersion: lambda.LambdaInsightsVersion.fromInsightVersionArn(layerArn),
379  });
380  ```
381  
382  ## Event Rule Target
383  
384  You can use an AWS Lambda function as a target for an Amazon CloudWatch event
385  rule:
386  
387  ```ts
388  import * as events from '@aws-cdk/aws-events';
389  import * as targets from '@aws-cdk/aws-events-targets';
390  
391  declare const fn: lambda.Function;
392  const rule = new events.Rule(this, 'Schedule Rule', {
393   schedule: events.Schedule.cron({ minute: '0', hour: '4' }),
394  });
395  rule.addTarget(new targets.LambdaFunction(fn));
396  ```
397  
398  ## Event Sources
399  
400  AWS Lambda supports a [variety of event sources](https://docs.aws.amazon.com/lambda/latest/dg/invoking-lambda-function.html).
401  
402  In most cases, it is possible to trigger a function as a result of an event by
403  using one of the `add<Event>Notification` methods on the source construct. For
404  example, the `s3.Bucket` construct has an `onEvent` method which can be used to
405  trigger a Lambda when an event, such as PutObject occurs on an S3 bucket.
406  
407  An alternative way to add event sources to a function is to use `function.addEventSource(source)`.
408  This method accepts an `IEventSource` object. The module __@aws-cdk/aws-lambda-event-sources__
409  includes classes for the various event sources supported by AWS Lambda.
410  
411  For example, the following code adds an SQS queue as an event source for a function:
412  
413  ```ts
414  import * as eventsources from '@aws-cdk/aws-lambda-event-sources';
415  import * as sqs from '@aws-cdk/aws-sqs';
416  
417  declare const fn: lambda.Function;
418  const queue = new sqs.Queue(this, 'Queue');
419  fn.addEventSource(new eventsources.SqsEventSource(queue));
420  ```
421  
422  The following code adds an S3 bucket notification as an event source:
423  
424  ```ts
425  import * as eventsources from '@aws-cdk/aws-lambda-event-sources';
426  import * as s3 from '@aws-cdk/aws-s3';
427  
428  declare const fn: lambda.Function;
429  const bucket = new s3.Bucket(this, 'Bucket');
430  fn.addEventSource(new eventsources.S3EventSource(bucket, {
431    events: [ s3.EventType.OBJECT_CREATED, s3.EventType.OBJECT_REMOVED ],
432    filters: [ { prefix: 'subdir/' } ] // optional
433  }));
434  ```
435  
436  See the documentation for the __@aws-cdk/aws-lambda-event-sources__ module for more details.
437  
438  ## Lambda with DLQ
439  
440  A dead-letter queue can be automatically created for a Lambda function by
441  setting the `deadLetterQueueEnabled: true` configuration.
442  
443  ```ts
444  const fn = new lambda.Function(this, 'MyFunction', {
445    runtime: lambda.Runtime.NODEJS_12_X,
446    handler: 'index.handler',
447    code: lambda.Code.fromInline('exports.handler = function(event, ctx, cb) { return cb(null, "hi"); }'),
448    deadLetterQueueEnabled: true,
449  });
450  ```
451  
452  It is also possible to provide a dead-letter queue instead of getting a new queue created:
453  
454  ```ts
455  import * as sqs from '@aws-cdk/aws-sqs';
456  
457  const dlq = new sqs.Queue(this, 'DLQ');
458  const fn = new lambda.Function(this, 'MyFunction', {
459    runtime: lambda.Runtime.NODEJS_12_X,
460    handler: 'index.handler',
461    code: lambda.Code.fromInline('exports.handler = function(event, ctx, cb) { return cb(null, "hi"); }'),
462    deadLetterQueue: dlq,
463  });
464  ```
465  
466  See [the AWS documentation](https://docs.aws.amazon.com/lambda/latest/dg/dlq.html)
467  to learn more about AWS Lambdas and DLQs.
468  
469  ## Lambda with X-Ray Tracing
470  
471  ```ts
472  const fn = new lambda.Function(this, 'MyFunction', {
473    runtime: lambda.Runtime.NODEJS_12_X,
474    handler: 'index.handler',
475    code: lambda.Code.fromInline('exports.handler = function(event, ctx, cb) { return cb(null, "hi"); }'),
476    tracing: lambda.Tracing.ACTIVE,
477  });
478  ```
479  
480  See [the AWS documentation](https://docs.aws.amazon.com/lambda/latest/dg/lambda-x-ray.html)
481  to learn more about AWS Lambda's X-Ray support.
482  
483  ## Lambda with Profiling
484  
485  The following code configures the lambda function with CodeGuru profiling. By default, this creates a new CodeGuru
486  profiling group -
487  
488  ```ts
489  const fn = new lambda.Function(this, 'MyFunction', {
490    runtime: lambda.Runtime.PYTHON_3_6,
491    handler: 'index.handler',
492    code: lambda.Code.fromAsset('lambda-handler'),
493    profiling: true,
494  });
495  ```
496  
497  The `profilingGroup` property can be used to configure an existing CodeGuru profiler group.
498  
499  CodeGuru profiling is supported for all Java runtimes and Python3.6+ runtimes.
500  
501  See [the AWS documentation](https://docs.aws.amazon.com/codeguru/latest/profiler-ug/setting-up-lambda.html)
502  to learn more about AWS Lambda's Profiling support.
503  
504  ## Lambda with Reserved Concurrent Executions
505  
506  ```ts
507  const fn = new lambda.Function(this, 'MyFunction', {
508    runtime: lambda.Runtime.NODEJS_12_X,
509    handler: 'index.handler',
510    code: lambda.Code.fromInline('exports.handler = function(event, ctx, cb) { return cb(null, "hi"); }'),
511    reservedConcurrentExecutions: 100,
512  });
513  ```
514  
515  See [the AWS documentation](https://docs.aws.amazon.com/lambda/latest/dg/concurrent-executions.html)
516  managing concurrency.
517  
518  ## AutoScaling
519  
520  You can use Application AutoScaling to automatically configure the provisioned concurrency for your functions. AutoScaling can be set to track utilization or be based on a schedule. To configure AutoScaling on a function alias:
521  
522  ```ts
523  import * as autoscaling from '@aws-cdk/aws-autoscaling';
524  
525  declare const fn: lambda.Function;
526  const alias = new lambda.Alias(this, 'Alias', {
527    aliasName: 'prod',
528    version: fn.latestVersion,
529  });
530  
531  // Create AutoScaling target
532  const as = alias.addAutoScaling({ maxCapacity: 50 });
533  
534  // Configure Target Tracking
535  as.scaleOnUtilization({
536    utilizationTarget: 0.5,
537  });
538  
539  // Configure Scheduled Scaling
540  as.scaleOnSchedule('ScaleUpInTheMorning', {
541    schedule: autoscaling.Schedule.cron({ hour: '8', minute: '0'}),
542    minCapacity: 20,
543  });
544  ```
545  
546  [Example of Lambda AutoScaling usage](test/integ.autoscaling.lit.ts)
547  
548  See [the AWS documentation](https://docs.aws.amazon.com/lambda/latest/dg/invocation-scaling.html) on autoscaling lambda functions.
549  
550  ## Log Group
551  
552  Lambda functions automatically create a log group with the name `/aws/lambda/<function-name>` upon first execution with
553  log data set to never expire.
554  
555  The `logRetention` property can be used to set a different expiration period.
556  
557  It is possible to obtain the function's log group as a `logs.ILogGroup` by calling the `logGroup` property of the
558  `Function` construct.
559  
560  By default, CDK uses the AWS SDK retry options when creating a log group. The `logRetentionRetryOptions` property
561  allows you to customize the maximum number of retries and base backoff duration.
562  
563  *Note* that, if either `logRetention` is set or `logGroup` property is called, a [CloudFormation custom
564  resource](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cfn-customresource.html) is added
565  to the stack that pre-creates the log group as part of the stack deployment, if it already doesn't exist, and sets the
566  correct log retention period (never expire, by default).
567  
568  *Further note* that, if the log group already exists and the `logRetention` is not set, the custom resource will reset
569  the log retention to never expire even if it was configured with a different value.
570  
571  ## FileSystem Access
572  
573  You can configure a function to mount an Amazon Elastic File System (Amazon EFS) to a
574  directory in your runtime environment with the `filesystem` property. To access Amazon EFS
575  from lambda function, the Amazon EFS access point will be required.
576  
577  The following sample allows the lambda function to mount the Amazon EFS access point to `/mnt/msg` in the runtime environment and access the filesystem with the POSIX identity defined in `posixUser`.
578  
579  ```ts
580  import * as ec2 from '@aws-cdk/aws-ec2';
581  import * as efs from '@aws-cdk/aws-efs';
582  
583  // create a new VPC
584  const vpc = new ec2.Vpc(this, 'VPC');
585  
586  // create a new Amazon EFS filesystem
587  const fileSystem = new efs.FileSystem(this, 'Efs', { vpc });
588  
589  // create a new access point from the filesystem
590  const accessPoint = fileSystem.addAccessPoint('AccessPoint', {
591    // set /export/lambda as the root of the access point
592    path: '/export/lambda',
593    // as /export/lambda does not exist in a new efs filesystem, the efs will create the directory with the following createAcl
594    createAcl: {
595      ownerUid: '1001',
596      ownerGid: '1001',
597      permissions: '750',
598    },
599    // enforce the POSIX identity so lambda function will access with this identity
600    posixUser: {
601      uid: '1001',
602      gid: '1001',
603    },
604  });
605  
606  const fn = new lambda.Function(this, 'MyLambda', {
607    // mount the access point to /mnt/msg in the lambda runtime environment
608    filesystem: lambda.FileSystem.fromEfsAccessPoint(accessPoint, '/mnt/msg'),
609    runtime: lambda.Runtime.NODEJS_12_X,
610    handler: 'index.handler',
611    code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler')),
612    vpc,
613  });
614  ```
615  
616  
617  ## Singleton Function
618  
619  The `SingletonFunction` construct is a way to guarantee that a lambda function will be guaranteed to be part of the stack,
620  once and only once, irrespective of how many times the construct is declared to be part of the stack. This is guaranteed
621  as long as the `uuid` property and the optional `lambdaPurpose` property stay the same whenever they're declared into the
622  stack.
623  
624  A typical use case of this function is when a higher level construct needs to declare a Lambda function as part of it but
625  needs to guarantee that the function is declared once. However, a user of this higher level construct can declare it any
626  number of times and with different properties. Using `SingletonFunction` here with a fixed `uuid` will guarantee this.
627  
628  For example, the `LogRetention` construct requires only one single lambda function for all different log groups whose
629  retention it seeks to manage.
630  
631  ## Bundling Asset Code
632  
633  When using `lambda.Code.fromAsset(path)` it is possible to bundle the code by running a
634  command in a Docker container. The asset path will be mounted at `/asset-input`. The
635  Docker container is responsible for putting content at `/asset-output`. The content at
636  `/asset-output` will be zipped and used as Lambda code.
637  
638  Example with Python:
639  
640  ```ts
641  new lambda.Function(this, 'Function', {
642    code: lambda.Code.fromAsset(path.join(__dirname, 'my-python-handler'), {
643      bundling: {
644        image: lambda.Runtime.PYTHON_3_9.bundlingImage,
645        command: [
646          'bash', '-c',
647          'pip install -r requirements.txt -t /asset-output && cp -au . /asset-output'
648        ],
649      },
650    }),
651    runtime: lambda.Runtime.PYTHON_3_9,
652    handler: 'index.handler',
653  });
654  ```
655  
656  Runtimes expose a `bundlingImage` property that points to the [AWS SAM](https://github.com/awslabs/aws-sam-cli) build image.
657  
658  Use `cdk.DockerImage.fromRegistry(image)` to use an existing image or
659  `cdk.DockerImage.fromBuild(path)` to build a specific image:
660  
661  ```ts
662  new lambda.Function(this, 'Function', {
663    code: lambda.Code.fromAsset('/path/to/handler', {
664      bundling: {
665        image: DockerImage.fromBuild('/path/to/dir/with/DockerFile', {
666          buildArgs: {
667            ARG1: 'value1',
668          },
669        }),
670        command: ['my', 'cool', 'command'],
671      },
672    }),
673    runtime: lambda.Runtime.PYTHON_3_9,
674    handler: 'index.handler',
675  });
676  ```
677  
678  ## Language-specific APIs
679  
680  Language-specific higher level constructs are provided in separate modules:
681  
682  * `@aws-cdk/aws-lambda-nodejs`: [Github](https://github.com/aws/aws-cdk/tree/master/packages/%40aws-cdk/aws-lambda-nodejs) & [CDK Docs](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-lambda-nodejs-readme.html)
683  * `@aws-cdk/aws-lambda-python`: [Github](https://github.com/aws/aws-cdk/tree/master/packages/%40aws-cdk/aws-lambda-python) & [CDK Docs](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-lambda-python-readme.html)
684  
685  ## Code Signing
686  
687  Code signing for AWS Lambda helps to ensure that only trusted code runs in your Lambda functions.
688  When enabled, AWS Lambda checks every code deployment and verifies that the code package is signed by a trusted source.
689  For more information, see [Configuring code signing for AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/configuration-codesigning.html).
690  The following code configures a function with code signing.
691  
692  ```ts
693  import * as signer from '@aws-cdk/aws-signer';
694  
695  const signingProfile = new signer.SigningProfile(this, 'SigningProfile', {
696    platform: signer.Platform.AWS_LAMBDA_SHA384_ECDSA,
697  });
698  
699  const codeSigningConfig = new lambda.CodeSigningConfig(this, 'CodeSigningConfig', {
700    signingProfiles: [signingProfile],
701  });
702  
703  new lambda.Function(this, 'Function', {
704    codeSigningConfig,
705    runtime: lambda.Runtime.NODEJS_12_X,
706    handler: 'index.handler',
707    code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler')),
708  });
709  ```