UNPKG

23.7 kBTypeScriptView Raw
1import * as cloudwatch from '@aws-cdk/aws-cloudwatch';
2import { IProfilingGroup } from '@aws-cdk/aws-codeguruprofiler';
3import * as ec2 from '@aws-cdk/aws-ec2';
4import * as iam from '@aws-cdk/aws-iam';
5import * as kms from '@aws-cdk/aws-kms';
6import * as logs from '@aws-cdk/aws-logs';
7import * as sns from '@aws-cdk/aws-sns';
8import * as sqs from '@aws-cdk/aws-sqs';
9import { Duration, IAspect, IConstruct, Size } from '@aws-cdk/core';
10import { Construct } from 'constructs';
11import { AliasOptions, Alias } from './alias';
12import { Architecture } from './architecture';
13import { Code, CodeConfig } from './code';
14import { ICodeSigningConfig } from './code-signing-config';
15import { EventInvokeConfigOptions } from './event-invoke-config';
16import { IEventSource } from './event-source';
17import { FileSystem } from './filesystem';
18import { FunctionAttributes, FunctionBase, IFunction } from './function-base';
19import { LambdaInsightsVersion } from './lambda-insights';
20import { Version, VersionOptions } from './lambda-version';
21import { ILayerVersion } from './layers';
22import { Runtime } from './runtime';
23import { LogRetentionRetryOptions } from './log-retention';
24/**
25 * X-Ray Tracing Modes (https://docs.aws.amazon.com/lambda/latest/dg/API_TracingConfig.html)
26 */
27export declare enum Tracing {
28 /**
29 * Lambda will respect any tracing header it receives from an upstream service.
30 * If no tracing header is received, Lambda will call X-Ray for a tracing decision.
31 */
32 ACTIVE = "Active",
33 /**
34 * Lambda will only trace the request from an upstream service
35 * if it contains a tracing header with "sampled=1"
36 */
37 PASS_THROUGH = "PassThrough",
38 /**
39 * Lambda will not trace any request.
40 */
41 DISABLED = "Disabled"
42}
43/**
44 * Non runtime options
45 */
46export interface FunctionOptions extends EventInvokeConfigOptions {
47 /**
48 * A description of the function.
49 *
50 * @default - No description.
51 */
52 readonly description?: string;
53 /**
54 * The function execution time (in seconds) after which Lambda terminates
55 * the function. Because the execution time affects cost, set this value
56 * based on the function's expected execution time.
57 *
58 * @default Duration.seconds(3)
59 */
60 readonly timeout?: Duration;
61 /**
62 * Key-value pairs that Lambda caches and makes available for your Lambda
63 * functions. Use environment variables to apply configuration changes, such
64 * as test and production environment configurations, without changing your
65 * Lambda function source code.
66 *
67 * @default - No environment variables.
68 */
69 readonly environment?: {
70 [key: string]: string;
71 };
72 /**
73 * A name for the function.
74 *
75 * @default - AWS CloudFormation generates a unique physical ID and uses that
76 * ID for the function's name. For more information, see Name Type.
77 */
78 readonly functionName?: string;
79 /**
80 * The amount of memory, in MB, that is allocated to your Lambda function.
81 * Lambda uses this value to proportionally allocate the amount of CPU
82 * power. For more information, see Resource Model in the AWS Lambda
83 * Developer Guide.
84 *
85 * @default 128
86 */
87 readonly memorySize?: number;
88 /**
89 * The size of the function’s /tmp directory in MiB.
90 *
91 * @default 512 MiB
92 */
93 readonly ephemeralStorageSize?: Size;
94 /**
95 * Initial policy statements to add to the created Lambda Role.
96 *
97 * You can call `addToRolePolicy` to the created lambda to add statements post creation.
98 *
99 * @default - No policy statements are added to the created Lambda role.
100 */
101 readonly initialPolicy?: iam.PolicyStatement[];
102 /**
103 * Lambda execution role.
104 *
105 * This is the role that will be assumed by the function upon execution.
106 * It controls the permissions that the function will have. The Role must
107 * be assumable by the 'lambda.amazonaws.com' service principal.
108 *
109 * The default Role automatically has permissions granted for Lambda execution. If you
110 * provide a Role, you must add the relevant AWS managed policies yourself.
111 *
112 * The relevant managed policies are "service-role/AWSLambdaBasicExecutionRole" and
113 * "service-role/AWSLambdaVPCAccessExecutionRole".
114 *
115 * @default - A unique role will be generated for this lambda function.
116 * Both supplied and generated roles can always be changed by calling `addToRolePolicy`.
117 */
118 readonly role?: iam.IRole;
119 /**
120 * VPC network to place Lambda network interfaces
121 *
122 * Specify this if the Lambda function needs to access resources in a VPC.
123 *
124 * @default - Function is not placed within a VPC.
125 */
126 readonly vpc?: ec2.IVpc;
127 /**
128 * Where to place the network interfaces within the VPC.
129 *
130 * Only used if 'vpc' is supplied. Note: internet access for Lambdas
131 * requires a NAT gateway, so picking Public subnets is not allowed.
132 *
133 * @default - the Vpc default strategy if not specified
134 */
135 readonly vpcSubnets?: ec2.SubnetSelection;
136 /**
137 * What security group to associate with the Lambda's network interfaces.
138 * This property is being deprecated, consider using securityGroups instead.
139 *
140 * Only used if 'vpc' is supplied.
141 *
142 * Use securityGroups property instead.
143 * Function constructor will throw an error if both are specified.
144 *
145 * @default - If the function is placed within a VPC and a security group is
146 * not specified, either by this or securityGroups prop, a dedicated security
147 * group will be created for this function.
148 *
149 * @deprecated - This property is deprecated, use securityGroups instead
150 */
151 readonly securityGroup?: ec2.ISecurityGroup;
152 /**
153 * The list of security groups to associate with the Lambda's network interfaces.
154 *
155 * Only used if 'vpc' is supplied.
156 *
157 * @default - If the function is placed within a VPC and a security group is
158 * not specified, either by this or securityGroup prop, a dedicated security
159 * group will be created for this function.
160 */
161 readonly securityGroups?: ec2.ISecurityGroup[];
162 /**
163 * Whether to allow the Lambda to send all network traffic
164 *
165 * If set to false, you must individually add traffic rules to allow the
166 * Lambda to connect to network targets.
167 *
168 * @default true
169 */
170 readonly allowAllOutbound?: boolean;
171 /**
172 * Enabled DLQ. If `deadLetterQueue` is undefined,
173 * an SQS queue with default options will be defined for your Function.
174 *
175 * @default - false unless `deadLetterQueue` is set, which implies DLQ is enabled.
176 */
177 readonly deadLetterQueueEnabled?: boolean;
178 /**
179 * The SQS queue to use if DLQ is enabled.
180 * If SNS topic is desired, specify `deadLetterTopic` property instead.
181 *
182 * @default - SQS queue with 14 day retention period if `deadLetterQueueEnabled` is `true`
183 */
184 readonly deadLetterQueue?: sqs.IQueue;
185 /**
186 * The SNS topic to use as a DLQ.
187 * Note that if `deadLetterQueueEnabled` is set to `true`, an SQS queue will be created
188 * rather than an SNS topic. Using an SNS topic as a DLQ requires this property to be set explicitly.
189 *
190 * @default - no SNS topic
191 */
192 readonly deadLetterTopic?: sns.ITopic;
193 /**
194 * Enable AWS X-Ray Tracing for Lambda Function.
195 *
196 * @default Tracing.Disabled
197 */
198 readonly tracing?: Tracing;
199 /**
200 * Enable profiling.
201 * @see https://docs.aws.amazon.com/codeguru/latest/profiler-ug/setting-up-lambda.html
202 *
203 * @default - No profiling.
204 */
205 readonly profiling?: boolean;
206 /**
207 * Profiling Group.
208 * @see https://docs.aws.amazon.com/codeguru/latest/profiler-ug/setting-up-lambda.html
209 *
210 * @default - A new profiling group will be created if `profiling` is set.
211 */
212 readonly profilingGroup?: IProfilingGroup;
213 /**
214 * Specify the version of CloudWatch Lambda insights to use for monitoring
215 * @see https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Lambda-Insights.html
216 *
217 * When used with `DockerImageFunction` or `DockerImageCode`, the Docker image should have
218 * the Lambda insights agent installed.
219 * @see https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Lambda-Insights-Getting-Started-docker.html
220 *
221 * @default - No Lambda Insights
222 */
223 readonly insightsVersion?: LambdaInsightsVersion;
224 /**
225 * A list of layers to add to the function's execution environment. You can configure your Lambda function to pull in
226 * additional code during initialization in the form of layers. Layers are packages of libraries or other dependencies
227 * that can be used by multiple functions.
228 *
229 * @default - No layers.
230 */
231 readonly layers?: ILayerVersion[];
232 /**
233 * The maximum of concurrent executions you want to reserve for the function.
234 *
235 * @default - No specific limit - account limit.
236 * @see https://docs.aws.amazon.com/lambda/latest/dg/concurrent-executions.html
237 */
238 readonly reservedConcurrentExecutions?: number;
239 /**
240 * Event sources for this function.
241 *
242 * You can also add event sources using `addEventSource`.
243 *
244 * @default - No event sources.
245 */
246 readonly events?: IEventSource[];
247 /**
248 * The number of days log events are kept in CloudWatch Logs. When updating
249 * this property, unsetting it doesn't remove the log retention policy. To
250 * remove the retention policy, set the value to `INFINITE`.
251 *
252 * @default logs.RetentionDays.INFINITE
253 */
254 readonly logRetention?: logs.RetentionDays;
255 /**
256 * The IAM role for the Lambda function associated with the custom resource
257 * that sets the retention policy.
258 *
259 * @default - A new role is created.
260 */
261 readonly logRetentionRole?: iam.IRole;
262 /**
263 * When log retention is specified, a custom resource attempts to create the CloudWatch log group.
264 * These options control the retry policy when interacting with CloudWatch APIs.
265 *
266 * @default - Default AWS SDK retry options.
267 */
268 readonly logRetentionRetryOptions?: LogRetentionRetryOptions;
269 /**
270 * Options for the `lambda.Version` resource automatically created by the
271 * `fn.currentVersion` method.
272 * @default - default options as described in `VersionOptions`
273 */
274 readonly currentVersionOptions?: VersionOptions;
275 /**
276 * The filesystem configuration for the lambda function
277 *
278 * @default - will not mount any filesystem
279 */
280 readonly filesystem?: FileSystem;
281 /**
282 * Lambda Functions in a public subnet can NOT access the internet.
283 * Use this property to acknowledge this limitation and still place the function in a public subnet.
284 * @see https://stackoverflow.com/questions/52992085/why-cant-an-aws-lambda-function-inside-a-public-subnet-in-a-vpc-connect-to-the/52994841#52994841
285 *
286 * @default false
287 */
288 readonly allowPublicSubnet?: boolean;
289 /**
290 * The AWS KMS key that's used to encrypt your function's environment variables.
291 *
292 * @default - AWS Lambda creates and uses an AWS managed customer master key (CMK).
293 */
294 readonly environmentEncryption?: kms.IKey;
295 /**
296 * Code signing config associated with this function
297 *
298 * @default - Not Sign the Code
299 */
300 readonly codeSigningConfig?: ICodeSigningConfig;
301 /**
302 * DEPRECATED
303 * @default [Architecture.X86_64]
304 * @deprecated use `architecture`
305 */
306 readonly architectures?: Architecture[];
307 /**
308 * The system architectures compatible with this lambda function.
309 * @default Architecture.X86_64
310 */
311 readonly architecture?: Architecture;
312}
313export interface FunctionProps extends FunctionOptions {
314 /**
315 * The runtime environment for the Lambda function that you are uploading.
316 * For valid values, see the Runtime property in the AWS Lambda Developer
317 * Guide.
318 *
319 * Use `Runtime.FROM_IMAGE` when when defining a function from a Docker image.
320 */
321 readonly runtime: Runtime;
322 /**
323 * The source code of your Lambda function. You can point to a file in an
324 * Amazon Simple Storage Service (Amazon S3) bucket or specify your source
325 * code as inline text.
326 */
327 readonly code: Code;
328 /**
329 * The name of the method within your code that Lambda calls to execute
330 * your function. The format includes the file name. It can also include
331 * namespaces and other qualifiers, depending on the runtime.
332 * For more information, see https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-features.html#gettingstarted-features-programmingmodel.
333 *
334 * Use `Handler.FROM_IMAGE` when defining a function from a Docker image.
335 *
336 * NOTE: If you specify your source code as inline text by specifying the
337 * ZipFile property within the Code property, specify index.function_name as
338 * the handler.
339 */
340 readonly handler: string;
341}
342/**
343 * Deploys a file from inside the construct library as a function.
344 *
345 * The supplied file is subject to the 4096 bytes limit of being embedded in a
346 * CloudFormation template.
347 *
348 * The construct includes an associated role with the lambda.
349 *
350 * This construct does not yet reproduce all features from the underlying resource
351 * library.
352 */
353export declare class Function extends FunctionBase {
354 /**
355 * Returns a `lambda.Version` which represents the current version of this
356 * Lambda function. A new version will be created every time the function's
357 * configuration changes.
358 *
359 * You can specify options for this version using the `currentVersionOptions`
360 * prop when initializing the `lambda.Function`.
361 */
362 get currentVersion(): Version;
363 get resourceArnsForGrantInvoke(): string[];
364 /** @internal */
365 static _VER_PROPS: {
366 [key: string]: boolean;
367 };
368 /**
369 * Record whether specific properties in the `AWS::Lambda::Function` resource should
370 * also be associated to the Version resource.
371 * See 'currentVersion' section in the module README for more details.
372 * @param propertyName The property to classify
373 * @param locked whether the property should be associated to the version or not.
374 */
375 static classifyVersionProperty(propertyName: string, locked: boolean): void;
376 /**
377 * Import a lambda function into the CDK using its name
378 */
379 static fromFunctionName(scope: Construct, id: string, functionName: string): IFunction;
380 /**
381 * Import a lambda function into the CDK using its ARN
382 */
383 static fromFunctionArn(scope: Construct, id: string, functionArn: string): IFunction;
384 /**
385 * Creates a Lambda function object which represents a function not defined
386 * within this stack.
387 *
388 * @param scope The parent construct
389 * @param id The name of the lambda construct
390 * @param attrs the attributes of the function to import
391 */
392 static fromFunctionAttributes(scope: Construct, id: string, attrs: FunctionAttributes): IFunction;
393 /**
394 * Return the given named metric for this Lambda
395 */
396 static metricAll(metricName: string, props?: cloudwatch.MetricOptions): cloudwatch.Metric;
397 /**
398 * Metric for the number of Errors executing all Lambdas
399 *
400 * @default sum over 5 minutes
401 */
402 static metricAllErrors(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
403 /**
404 * Metric for the Duration executing all Lambdas
405 *
406 * @default average over 5 minutes
407 */
408 static metricAllDuration(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
409 /**
410 * Metric for the number of invocations of all Lambdas
411 *
412 * @default sum over 5 minutes
413 */
414 static metricAllInvocations(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
415 /**
416 * Metric for the number of throttled invocations of all Lambdas
417 *
418 * @default sum over 5 minutes
419 */
420 static metricAllThrottles(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
421 /**
422 * Metric for the number of concurrent executions across all Lambdas
423 *
424 * @default max over 5 minutes
425 */
426 static metricAllConcurrentExecutions(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
427 /**
428 * Metric for the number of unreserved concurrent executions across all Lambdas
429 *
430 * @default max over 5 minutes
431 */
432 static metricAllUnreservedConcurrentExecutions(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
433 /**
434 * Name of this function
435 */
436 readonly functionName: string;
437 /**
438 * ARN of this function
439 */
440 readonly functionArn: string;
441 /**
442 * Execution role associated with this function
443 */
444 readonly role?: iam.IRole;
445 /**
446 * The runtime configured for this lambda.
447 */
448 readonly runtime: Runtime;
449 /**
450 * The principal this Lambda Function is running as
451 */
452 readonly grantPrincipal: iam.IPrincipal;
453 /**
454 * The DLQ (as queue) associated with this Lambda Function (this is an optional attribute).
455 */
456 readonly deadLetterQueue?: sqs.IQueue;
457 /**
458 * The DLQ (as topic) associated with this Lambda Function (this is an optional attribute).
459 */
460 readonly deadLetterTopic?: sns.ITopic;
461 /**
462 * The architecture of this Lambda Function (this is an optional attribute and defaults to X86_64).
463 */
464 readonly architecture: Architecture;
465 /**
466 * The timeout configured for this lambda.
467 */
468 readonly timeout?: Duration;
469 readonly permissionsNode: import("@aws-cdk/core").ConstructNode;
470 protected readonly canCreatePermissions = true;
471 /** @internal */
472 readonly _layers: ILayerVersion[];
473 private _logGroup?;
474 /**
475 * Environment variables for this function
476 */
477 private environment;
478 private readonly currentVersionOptions?;
479 private _currentVersion?;
480 private _architecture?;
481 constructor(scope: Construct, id: string, props: FunctionProps);
482 /**
483 * Adds an environment variable to this Lambda function.
484 * If this is a ref to a Lambda function, this operation results in a no-op.
485 * @param key The environment variable key.
486 * @param value The environment variable's value.
487 * @param options Environment variable options.
488 */
489 addEnvironment(key: string, value: string, options?: EnvironmentOptions): this;
490 /**
491 * Adds one or more Lambda Layers to this Lambda function.
492 *
493 * @param layers the layers to be added.
494 *
495 * @throws if there are already 5 layers on this function, or the layer is incompatible with this function's runtime.
496 */
497 addLayers(...layers: ILayerVersion[]): void;
498 /**
499 * Add a new version for this Lambda
500 *
501 * If you want to deploy through CloudFormation and use aliases, you need to
502 * add a new version (with a new name) to your Lambda every time you want to
503 * deploy an update. An alias can then refer to the newly created Version.
504 *
505 * All versions should have distinct names, and you should not delete versions
506 * as long as your Alias needs to refer to them.
507 *
508 * @param name A unique name for this version.
509 * @param codeSha256 The SHA-256 hash of the most recently deployed Lambda
510 * source code, or omit to skip validation.
511 * @param description A description for this version.
512 * @param provisionedExecutions A provisioned concurrency configuration for a
513 * function's version.
514 * @param asyncInvokeConfig configuration for this version when it is invoked
515 * asynchronously.
516 * @returns A new Version object.
517 *
518 * @deprecated This method will create an AWS::Lambda::Version resource which
519 * snapshots the AWS Lambda function *at the time of its creation* and it
520 * won't get updated when the function changes. Instead, use
521 * `this.currentVersion` to obtain a reference to a version resource that gets
522 * automatically recreated when the function configuration (or code) changes.
523 */
524 addVersion(name: string, codeSha256?: string, description?: string, provisionedExecutions?: number, asyncInvokeConfig?: EventInvokeConfigOptions): Version;
525 /**
526 * Defines an alias for this function.
527 *
528 * The alias will automatically be updated to point to the latest version of
529 * the function as it is being updated during a deployment.
530 *
531 * ```ts
532 * declare const fn: lambda.Function;
533 *
534 * fn.addAlias('Live');
535 *
536 * // Is equivalent to
537 *
538 * new lambda.Alias(this, 'AliasLive', {
539 * aliasName: 'Live',
540 * version: fn.currentVersion,
541 * });
542 *
543 * @param aliasName The name of the alias
544 * @param options Alias options
545 */
546 addAlias(aliasName: string, options?: AliasOptions): Alias;
547 /**
548 * The LogGroup where the Lambda function's logs are made available.
549 *
550 * If either `logRetention` is set or this property is called, a CloudFormation custom resource is added to the stack that
551 * pre-creates the log group as part of the stack deployment, if it already doesn't exist, and sets the correct log retention
552 * period (never expire, by default).
553 *
554 * Further, if the log group already exists and the `logRetention` is not set, the custom resource will reset the log retention
555 * to never expire even if it was configured with a different value.
556 */
557 get logGroup(): logs.ILogGroup;
558 /** @internal */
559 _checkEdgeCompatibility(): void;
560 /**
561 * Configured lambda insights on the function if specified. This is acheived by adding an imported layer which is added to the
562 * list of lambda layers on synthesis.
563 *
564 * https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Lambda-Insights-extension-versions.html
565 */
566 private configureLambdaInsights;
567 private renderLayers;
568 private renderEnvironment;
569 /**
570 * If configured, set up the VPC-related properties
571 *
572 * Returns the VpcConfig that should be added to the
573 * Lambda creation properties.
574 */
575 private configureVpc;
576 private isQueue;
577 private buildDeadLetterQueue;
578 private buildDeadLetterConfig;
579 private buildTracingConfig;
580 private validateProfiling;
581}
582/**
583 * Environment variables options
584 */
585export interface EnvironmentOptions {
586 /**
587 * When used in Lambda@Edge via edgeArn() API, these environment
588 * variables will be removed. If not set, an error will be thrown.
589 * @see https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-requirements-limits.html#lambda-requirements-lambda-function-configuration
590 *
591 * @default false - using the function in Lambda@Edge will throw
592 */
593 readonly removeInEdge?: boolean;
594}
595export declare function verifyCodeConfig(code: CodeConfig, props: FunctionProps): void;
596/**
597 * Aspect for upgrading function versions when the feature flag
598 * provided feature flag present. This can be necessary when the feature flag
599 * changes the function hash, as such changes must be associated with a new
600 * version. This aspect will change the function description in these cases,
601 * which "validates" the new function hash.
602 */
603export declare class FunctionVersionUpgrade implements IAspect {
604 private readonly featureFlag;
605 private readonly enabled;
606 constructor(featureFlag: string, enabled?: boolean);
607 visit(node: IConstruct): void;
608}