-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
function.ts
1726 lines (1534 loc) · 62.6 KB
/
function.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Construct, IConstruct } from 'constructs';
import { AdotInstrumentationConfig, AdotLambdaExecWrapper } from './adot-layers';
import { AliasOptions, Alias } from './alias';
import { Architecture } from './architecture';
import { Code, CodeConfig } from './code';
import { ICodeSigningConfig } from './code-signing-config';
import { EventInvokeConfigOptions } from './event-invoke-config';
import { IEventSource } from './event-source';
import { FileSystem } from './filesystem';
import { FunctionAttributes, FunctionBase, IFunction } from './function-base';
import { calculateFunctionHash, trimFromStart } from './function-hash';
import { Handler } from './handler';
import { LambdaInsightsVersion } from './lambda-insights';
import { Version, VersionOptions } from './lambda-version';
import { CfnFunction } from './lambda.generated';
import { LayerVersion, ILayerVersion } from './layers';
import { LogRetentionRetryOptions } from './log-retention';
import { ParamsAndSecretsLayerVersion } from './params-and-secrets-layers';
import { Runtime, RuntimeFamily } from './runtime';
import { RuntimeManagementMode } from './runtime-management';
import { SnapStartConf } from './snapstart-config';
import { addAlias } from './util';
import * as cloudwatch from '../../aws-cloudwatch';
import { IProfilingGroup, ProfilingGroup, ComputePlatform } from '../../aws-codeguruprofiler';
import * as ec2 from '../../aws-ec2';
import * as efs from '../../aws-efs';
import * as iam from '../../aws-iam';
import * as kms from '../../aws-kms';
import * as logs from '../../aws-logs';
import * as sns from '../../aws-sns';
import * as sqs from '../../aws-sqs';
import { Annotations, ArnFormat, CfnResource, Duration, FeatureFlags, Fn, IAspect, Lazy, Names, Size, Stack, Token } from '../../core';
import { LAMBDA_RECOGNIZE_LAYER_VERSION } from '../../cx-api';
/**
* X-Ray Tracing Modes (https://docs.aws.amazon.com/lambda/latest/dg/API_TracingConfig.html)
*/
export enum Tracing {
/**
* Lambda will respect any tracing header it receives from an upstream service.
* If no tracing header is received, Lambda will sample the request based on a fixed rate. Please see the [Using AWS Lambda with AWS X-Ray](https://docs.aws.amazon.com/lambda/latest/dg/services-xray.html) documentation for details on this sampling behavior.
*/
ACTIVE = 'Active',
/**
* Lambda will only trace the request from an upstream service
* if it contains a tracing header with "sampled=1"
*/
PASS_THROUGH = 'PassThrough',
/**
* Lambda will not trace any request.
*/
DISABLED = 'Disabled',
}
/**
* Lambda service will automatically captures system logs about function invocation
* generated by the Lambda service (known as system logs) and sends these logs to a
* default CloudWatch log group named after the Lambda function.
*/
export enum SystemLogLevel {
/**
* Lambda will capture only logs at info level.
*/
INFO = 'INFO',
/**
* Lambda will capture only logs at debug level.
*/
DEBUG = 'DEBUG',
/**
* Lambda will capture only logs at warn level.
*/
WARN = 'WARN',
}
/**
* Lambda service automatically captures logs generated by the function code
* (known as application logs) and sends these logs to a default CloudWatch
* log group named after the Lambda function.
*/
export enum ApplicationLogLevel {
/**
* Lambda will capture only logs at info level.
*/
INFO = 'INFO',
/**
* Lambda will capture only logs at debug level.
*/
DEBUG = 'DEBUG',
/**
* Lambda will capture only logs at warn level.
*/
WARN = 'WARN',
/**
* Lambda will capture only logs at trace level.
*/
TRACE = 'TRACE',
/**
* Lambda will capture only logs at error level.
*/
ERROR = 'ERROR',
/**
* Lambda will capture only logs at fatal level.
*/
FATAL = 'FATAL',
}
/**
* This field takes in 2 values either Text or JSON. By setting this value to Text,
* will result in the current structure of logs format, whereas, by setting this value to JSON,
* Lambda will print the logs as Structured JSON Logs, with the corresponding timestamp and log level
* of each event. Selecting ‘JSON’ format will only allow customer’s to have different log level
* Application log level and the System log level.
*/
export enum LogFormat {
/**
* Lambda Logs text format.
*/
TEXT = 'Text',
/**
* Lambda structured logging in Json format.
*/
JSON = 'JSON',
}
/**
* This field takes in 2 values either Text or JSON. By setting this value to Text,
* will result in the current structure of logs format, whereas, by setting this value to JSON,
* Lambda will print the logs as Structured JSON Logs, with the corresponding timestamp and log level
* of each event. Selecting ‘JSON’ format will only allow customer’s to have different log level
* Application log level and the System log level.
*/
export enum LoggingFormat {
/**
* Lambda Logs text format.
*/
TEXT = 'Text',
/**
* Lambda structured logging in Json format.
*/
JSON = 'JSON',
}
/**
* Non runtime options
*/
export interface FunctionOptions extends EventInvokeConfigOptions {
/**
* A description of the function.
*
* @default - No description.
*/
readonly description?: string;
/**
* The function execution time (in seconds) after which Lambda terminates
* the function. Because the execution time affects cost, set this value
* based on the function's expected execution time.
*
* @default Duration.seconds(3)
*/
readonly timeout?: Duration;
/**
* Key-value pairs that Lambda caches and makes available for your Lambda
* functions. Use environment variables to apply configuration changes, such
* as test and production environment configurations, without changing your
* Lambda function source code.
*
* @default - No environment variables.
*/
readonly environment?: { [key: string]: string };
/**
* A name for the function.
*
* @default - AWS CloudFormation generates a unique physical ID and uses that
* ID for the function's name. For more information, see Name Type.
*/
readonly functionName?: string;
/**
* The amount of memory, in MB, that is allocated to your Lambda function.
* Lambda uses this value to proportionally allocate the amount of CPU
* power. For more information, see Resource Model in the AWS Lambda
* Developer Guide.
*
* @default 128
*/
readonly memorySize?: number;
/**
* The size of the function’s /tmp directory in MiB.
*
* @default 512 MiB
*/
readonly ephemeralStorageSize?: Size;
/**
* Initial policy statements to add to the created Lambda Role.
*
* You can call `addToRolePolicy` to the created lambda to add statements post creation.
*
* @default - No policy statements are added to the created Lambda role.
*/
readonly initialPolicy?: iam.PolicyStatement[];
/**
* Lambda execution role.
*
* This is the role that will be assumed by the function upon execution.
* It controls the permissions that the function will have. The Role must
* be assumable by the 'lambda.amazonaws.com' service principal.
*
* The default Role automatically has permissions granted for Lambda execution. If you
* provide a Role, you must add the relevant AWS managed policies yourself.
*
* The relevant managed policies are "service-role/AWSLambdaBasicExecutionRole" and
* "service-role/AWSLambdaVPCAccessExecutionRole".
*
* @default - A unique role will be generated for this lambda function.
* Both supplied and generated roles can always be changed by calling `addToRolePolicy`.
*/
readonly role?: iam.IRole;
/**
* VPC network to place Lambda network interfaces
*
* Specify this if the Lambda function needs to access resources in a VPC.
* This is required when `vpcSubnets` is specified.
*
* @default - Function is not placed within a VPC.
*/
readonly vpc?: ec2.IVpc;
/**
* Allows outbound IPv6 traffic on VPC functions that are connected to dual-stack subnets.
*
* Only used if 'vpc' is supplied.
*
* @default false
*/
readonly ipv6AllowedForDualStack?: boolean;
/**
* Where to place the network interfaces within the VPC.
*
* This requires `vpc` to be specified in order for interfaces to actually be
* placed in the subnets. If `vpc` is not specify, this will raise an error.
*
* Note: Internet access for Lambda Functions requires a NAT Gateway, so picking
* public subnets is not allowed (unless `allowPublicSubnet` is set to `true`).
*
* @default - the Vpc default strategy if not specified
*/
readonly vpcSubnets?: ec2.SubnetSelection;
/**
* What security group to associate with the Lambda's network interfaces.
* This property is being deprecated, consider using securityGroups instead.
*
* Only used if 'vpc' is supplied.
*
* Use securityGroups property instead.
* Function constructor will throw an error if both are specified.
*
* @default - If the function is placed within a VPC and a security group is
* not specified, either by this or securityGroups prop, a dedicated security
* group will be created for this function.
*
* @deprecated - This property is deprecated, use securityGroups instead
*/
readonly securityGroup?: ec2.ISecurityGroup;
/**
* The list of security groups to associate with the Lambda's network interfaces.
*
* Only used if 'vpc' is supplied.
*
* @default - If the function is placed within a VPC and a security group is
* not specified, either by this or securityGroup prop, a dedicated security
* group will be created for this function.
*/
readonly securityGroups?: ec2.ISecurityGroup[];
/**
* Whether to allow the Lambda to send all network traffic
*
* If set to false, you must individually add traffic rules to allow the
* Lambda to connect to network targets.
*
* Do not specify this property if the `securityGroups` or `securityGroup` property is set.
* Instead, configure `allowAllOutbound` directly on the security group.
*
* @default true
*/
readonly allowAllOutbound?: boolean;
/**
* Enabled DLQ. If `deadLetterQueue` is undefined,
* an SQS queue with default options will be defined for your Function.
*
* @default - false unless `deadLetterQueue` is set, which implies DLQ is enabled.
*/
readonly deadLetterQueueEnabled?: boolean;
/**
* The SQS queue to use if DLQ is enabled.
* If SNS topic is desired, specify `deadLetterTopic` property instead.
*
* @default - SQS queue with 14 day retention period if `deadLetterQueueEnabled` is `true`
*/
readonly deadLetterQueue?: sqs.IQueue;
/**
* The SNS topic to use as a DLQ.
* Note that if `deadLetterQueueEnabled` is set to `true`, an SQS queue will be created
* rather than an SNS topic. Using an SNS topic as a DLQ requires this property to be set explicitly.
*
* @default - no SNS topic
*/
readonly deadLetterTopic?: sns.ITopic;
/**
* Enable AWS X-Ray Tracing for Lambda Function.
*
* @default Tracing.Disabled
*/
readonly tracing?: Tracing;
/**
* Enable SnapStart for Lambda Function.
* SnapStart is currently supported only for Java 11, 17 runtime
*
* @default - No snapstart
*/
readonly snapStart?: SnapStartConf;
/**
* Enable profiling.
* @see https://docs.aws.amazon.com/codeguru/latest/profiler-ug/setting-up-lambda.html
*
* @default - No profiling.
*/
readonly profiling?: boolean;
/**
* Profiling Group.
* @see https://docs.aws.amazon.com/codeguru/latest/profiler-ug/setting-up-lambda.html
*
* @default - A new profiling group will be created if `profiling` is set.
*/
readonly profilingGroup?: IProfilingGroup;
/**
* Specify the version of CloudWatch Lambda insights to use for monitoring
* @see https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Lambda-Insights.html
*
* When used with `DockerImageFunction` or `DockerImageCode`, the Docker image should have
* the Lambda insights agent installed.
* @see https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Lambda-Insights-Getting-Started-docker.html
*
* @default - No Lambda Insights
*/
readonly insightsVersion?: LambdaInsightsVersion;
/**
* Specify the configuration of AWS Distro for OpenTelemetry (ADOT) instrumentation
* @see https://aws-otel.github.io/docs/getting-started/lambda
*
* @default - No ADOT instrumentation
*/
readonly adotInstrumentation?: AdotInstrumentationConfig;
/**
* Specify the configuration of Parameters and Secrets Extension
* @see https://docs.aws.amazon.com/secretsmanager/latest/userguide/retrieving-secrets_lambda.html
* @see https://docs.aws.amazon.com/systems-manager/latest/userguide/ps-integration-lambda-extensions.html
*
* @default - No Parameters and Secrets Extension
*/
readonly paramsAndSecrets?: ParamsAndSecretsLayerVersion;
/**
* A list of layers to add to the function's execution environment. You can configure your Lambda function to pull in
* additional code during initialization in the form of layers. Layers are packages of libraries or other dependencies
* that can be used by multiple functions.
*
* @default - No layers.
*/
readonly layers?: ILayerVersion[];
/**
* The maximum of concurrent executions you want to reserve for the function.
*
* @default - No specific limit - account limit.
* @see https://docs.aws.amazon.com/lambda/latest/dg/concurrent-executions.html
*/
readonly reservedConcurrentExecutions?: number;
/**
* Event sources for this function.
*
* You can also add event sources using `addEventSource`.
*
* @default - No event sources.
*/
readonly events?: IEventSource[];
/**
* The number of days log events are kept in CloudWatch Logs. When updating
* this property, unsetting it doesn't remove the log retention policy. To
* remove the retention policy, set the value to `INFINITE`.
*
* This is a legacy API and we strongly recommend you move away from it if you can.
* Instead create a fully customizable log group with `logs.LogGroup` and use the `logGroup` property
* to instruct the Lambda function to send logs to it.
* Migrating from `logRetention` to `logGroup` will cause the name of the log group to change.
* Users and code and referencing the name verbatim will have to adjust.
*
* In AWS CDK code, you can access the log group name directly from the LogGroup construct:
* ```ts
* import * as logs from 'aws-cdk-lib/aws-logs';
*
* declare const myLogGroup: logs.LogGroup;
* myLogGroup.logGroupName;
* ```
*
* @default logs.RetentionDays.INFINITE
*/
readonly logRetention?: logs.RetentionDays;
/**
* The IAM role for the Lambda function associated with the custom resource
* that sets the retention policy.
*
* This is a legacy API and we strongly recommend you migrate to `logGroup` if you can.
* `logGroup` allows you to create a fully customizable log group and instruct the Lambda function to send logs to it.
*
* @default - A new role is created.
*/
readonly logRetentionRole?: iam.IRole;
/**
* When log retention is specified, a custom resource attempts to create the CloudWatch log group.
* These options control the retry policy when interacting with CloudWatch APIs.
*
* This is a legacy API and we strongly recommend you migrate to `logGroup` if you can.
* `logGroup` allows you to create a fully customizable log group and instruct the Lambda function to send logs to it.
*
* @default - Default AWS SDK retry options.
*/
readonly logRetentionRetryOptions?: LogRetentionRetryOptions;
/**
* Options for the `lambda.Version` resource automatically created by the
* `fn.currentVersion` method.
* @default - default options as described in `VersionOptions`
*/
readonly currentVersionOptions?: VersionOptions;
/**
* The filesystem configuration for the lambda function
*
* @default - will not mount any filesystem
*/
readonly filesystem?: FileSystem;
/**
* Lambda Functions in a public subnet can NOT access the internet.
* Use this property to acknowledge this limitation and still place the function in a public subnet.
* @see https://stackoverflow.com/questions/52992085/why-cant-an-aws-lambda-function-inside-a-public-subnet-in-a-vpc-connect-to-the/52994841#52994841
*
* @default false
*/
readonly allowPublicSubnet?: boolean;
/**
* The AWS KMS key that's used to encrypt your function's environment variables.
*
* @default - AWS Lambda creates and uses an AWS managed customer master key (CMK).
*/
readonly environmentEncryption?: kms.IKey;
/**
* Code signing config associated with this function
*
* @default - Not Sign the Code
*/
readonly codeSigningConfig?: ICodeSigningConfig;
/**
* DEPRECATED
* @default [Architecture.X86_64]
* @deprecated use `architecture`
*/
readonly architectures?: Architecture[];
/**
* The system architectures compatible with this lambda function.
* @default Architecture.X86_64
*/
readonly architecture?: Architecture;
/**
* Sets the runtime management configuration for a function's version.
* @default Auto
*/
readonly runtimeManagementMode?: RuntimeManagementMode;
/**
* The log group the function sends logs to.
*
* By default, Lambda functions send logs to an automatically created default log group named /aws/lambda/\<function name\>.
* However you cannot change the properties of this auto-created log group using the AWS CDK, e.g. you cannot set a different log retention.
*
* Use the `logGroup` property to create a fully customizable LogGroup ahead of time, and instruct the Lambda function to send logs to it.
*
* Providing a user-controlled log group was rolled out to commercial regions on 2023-11-16.
* If you are deploying to another type of region, please check regional availability first.
*
* @default `/aws/lambda/${this.functionName}` - default log group created by Lambda
*/
readonly logGroup?: logs.ILogGroup;
/**
* Sets the logFormat for the function.
* @default "Text"
*/
readonly logFormat?: string;
/**
* Sets the loggingFormat for the function.
* @default LoggingFormat.TEXT
*/
readonly loggingFormat?: LoggingFormat;
/**
* Sets the application log level for the function.
* @default "INFO"
*/
readonly applicationLogLevel?: string;
/**
* Sets the system log level for the function.
* @default "INFO"
*/
readonly systemLogLevel?: string;
}
export interface FunctionProps extends FunctionOptions {
/**
* The runtime environment for the Lambda function that you are uploading.
* For valid values, see the Runtime property in the AWS Lambda Developer
* Guide.
*
* Use `Runtime.FROM_IMAGE` when defining a function from a Docker image.
*/
readonly runtime: Runtime;
/**
* The source code of your Lambda function. You can point to a file in an
* Amazon Simple Storage Service (Amazon S3) bucket or specify your source
* code as inline text.
*/
readonly code: Code;
/**
* The name of the method within your code that Lambda calls to execute
* your function. The format includes the file name. It can also include
* namespaces and other qualifiers, depending on the runtime.
* For more information, see https://docs.aws.amazon.com/lambda/latest/dg/foundation-progmodel.html.
*
* Use `Handler.FROM_IMAGE` when defining a function from a Docker image.
*
* NOTE: If you specify your source code as inline text by specifying the
* ZipFile property within the Code property, specify index.function_name as
* the handler.
*/
readonly handler: string;
}
/**
* Deploys a file from inside the construct library as a function.
*
* The supplied file is subject to the 4096 bytes limit of being embedded in a
* CloudFormation template.
*
* The construct includes an associated role with the lambda.
*
* This construct does not yet reproduce all features from the underlying resource
* library.
*/
export class Function extends FunctionBase {
/**
* Returns a `lambda.Version` which represents the current version of this
* Lambda function. A new version will be created every time the function's
* configuration changes.
*
* You can specify options for this version using the `currentVersionOptions`
* prop when initializing the `lambda.Function`.
*/
public get currentVersion(): Version {
if (this._currentVersion) {
return this._currentVersion;
}
if (this._warnIfCurrentVersionCalled) {
this.warnInvokeFunctionPermissions(this);
};
this._currentVersion = new Version(this, 'CurrentVersion', {
lambda: this,
...this.currentVersionOptions,
});
// override the version's logical ID with a lazy string which includes the
// hash of the function itself, so a new version resource is created when
// the function configuration changes.
const cfn = this._currentVersion.node.defaultChild as CfnResource;
const originalLogicalId = this.stack.resolve(cfn.logicalId) as string;
cfn.overrideLogicalId(Lazy.uncachedString({
produce: () => {
const hash = calculateFunctionHash(this, this.hashMixins.join(''));
const logicalId = trimFromStart(originalLogicalId, 255 - 32);
return `${logicalId}${hash}`;
},
}));
return this._currentVersion;
}
public get resourceArnsForGrantInvoke() {
return [this.functionArn, `${this.functionArn}:*`];
}
/** @internal */
public static _VER_PROPS: { [key: string]: boolean } = {};
/**
* Record whether specific properties in the `AWS::Lambda::Function` resource should
* also be associated to the Version resource.
* See 'currentVersion' section in the module README for more details.
* @param propertyName The property to classify
* @param locked whether the property should be associated to the version or not.
*/
public static classifyVersionProperty(propertyName: string, locked: boolean) {
this._VER_PROPS[propertyName] = locked;
}
/**
* Import a lambda function into the CDK using its name
*/
public static fromFunctionName(scope: Construct, id: string, functionName: string): IFunction {
return Function.fromFunctionAttributes(scope, id, {
functionArn: Stack.of(scope).formatArn({
service: 'lambda',
resource: 'function',
resourceName: functionName,
arnFormat: ArnFormat.COLON_RESOURCE_NAME,
}),
sameEnvironment: true,
});
}
/**
* Import a lambda function into the CDK using its ARN.
*
* For `Function.addPermissions()` to work on this imported lambda, make sure that is
* in the same account and region as the stack you are importing it into.
*/
public static fromFunctionArn(scope: Construct, id: string, functionArn: string): IFunction {
/**
* If the functionArn has a trailing version or alias (more than 7 parts when split by ":",
* we trim off the trailing version/alias to retrieve the real functionArn.
* See lambda resource ARN format here: https://docs.aws.amazon.com/lambda/latest/dg/lambda-api-permissions-ref.html
*/
const parts = functionArn.split(':');
if (parts.length > 7) {
const _functionArn = parts.slice(0, 7).join(':');
return Function.fromFunctionAttributes(scope, id, { functionArn: _functionArn });
} else {
return Function.fromFunctionAttributes(scope, id, { functionArn });
}
}
/**
* Creates a Lambda function object which represents a function not defined
* within this stack.
*
* For `Function.addPermissions()` to work on this imported lambda, set the sameEnvironment property to true
* if this imported lambda is in the same account and region as the stack you are importing it into.
*
* @param scope The parent construct
* @param id The name of the lambda construct
* @param attrs the attributes of the function to import
*/
public static fromFunctionAttributes(scope: Construct, id: string, attrs: FunctionAttributes): IFunction {
const functionArn = attrs.functionArn;
const functionName = extractNameFromArn(attrs.functionArn);
const role = attrs.role;
class Import extends FunctionBase {
public readonly functionName = functionName;
public readonly functionArn = functionArn;
public readonly grantPrincipal: iam.IPrincipal;
public readonly role = role;
public readonly permissionsNode = this.node;
public readonly architecture = attrs.architecture ?? Architecture.X86_64;
public readonly resourceArnsForGrantInvoke = [this.functionArn, `${this.functionArn}:*`];
protected readonly canCreatePermissions = attrs.sameEnvironment ?? this._isStackAccount();
protected readonly _skipPermissions = attrs.skipPermissions ?? false;
constructor(s: Construct, i: string) {
super(s, i, {
environmentFromArn: functionArn,
});
this.grantPrincipal = role || new iam.UnknownPrincipal({ resource: this });
if (attrs.securityGroup) {
this._connections = new ec2.Connections({
securityGroups: [attrs.securityGroup],
});
} else if (attrs.securityGroupId) {
this._connections = new ec2.Connections({
securityGroups: [ec2.SecurityGroup.fromSecurityGroupId(scope, 'SecurityGroup', attrs.securityGroupId)],
});
}
}
}
return new Import(scope, id);
}
/**
* Return the given named metric for this Lambda
*/
public static metricAll(metricName: string, props?: cloudwatch.MetricOptions): cloudwatch.Metric {
return new cloudwatch.Metric({
namespace: 'AWS/Lambda',
metricName,
...props,
});
}
/**
* Metric for the number of Errors executing all Lambdas
*
* @default sum over 5 minutes
*/
public static metricAllErrors(props?: cloudwatch.MetricOptions): cloudwatch.Metric {
return this.metricAll('Errors', { statistic: 'sum', ...props });
}
/**
* Metric for the Duration executing all Lambdas
*
* @default average over 5 minutes
*/
public static metricAllDuration(props?: cloudwatch.MetricOptions): cloudwatch.Metric {
return this.metricAll('Duration', props);
}
/**
* Metric for the number of invocations of all Lambdas
*
* @default sum over 5 minutes
*/
public static metricAllInvocations(props?: cloudwatch.MetricOptions): cloudwatch.Metric {
return this.metricAll('Invocations', { statistic: 'sum', ...props });
}
/**
* Metric for the number of throttled invocations of all Lambdas
*
* @default sum over 5 minutes
*/
public static metricAllThrottles(props?: cloudwatch.MetricOptions): cloudwatch.Metric {
return this.metricAll('Throttles', { statistic: 'sum', ...props });
}
/**
* Metric for the number of concurrent executions across all Lambdas
*
* @default max over 5 minutes
*/
public static metricAllConcurrentExecutions(props?: cloudwatch.MetricOptions): cloudwatch.Metric {
// Mini-FAQ: why max? This metric is a gauge that is emitted every
// minute, so either max or avg or a percentile make sense (but sum
// doesn't). Max is more sensitive to spiky load changes which is
// probably what you're interested in if you're looking at this metric
// (Load spikes may lead to concurrent execution errors that would
// otherwise not be visible in the avg)
return this.metricAll('ConcurrentExecutions', { statistic: 'max', ...props });
}
/**
* Metric for the number of unreserved concurrent executions across all Lambdas
*
* @default max over 5 minutes
*/
public static metricAllUnreservedConcurrentExecutions(props?: cloudwatch.MetricOptions): cloudwatch.Metric {
return this.metricAll('UnreservedConcurrentExecutions', { statistic: 'max', ...props });
}
/**
* Name of this function
*/
public readonly functionName: string;
/**
* ARN of this function
*/
public readonly functionArn: string;
/**
* Execution role associated with this function
*/
public readonly role?: iam.IRole;
/**
* The runtime configured for this lambda.
*/
public readonly runtime: Runtime;
/**
* The principal this Lambda Function is running as
*/
public readonly grantPrincipal: iam.IPrincipal;
/**
* The DLQ (as queue) associated with this Lambda Function (this is an optional attribute).
*/
public readonly deadLetterQueue?: sqs.IQueue;
/**
* The DLQ (as topic) associated with this Lambda Function (this is an optional attribute).
*/
public readonly deadLetterTopic?: sns.ITopic;
/**
* The architecture of this Lambda Function (this is an optional attribute and defaults to X86_64).
*/
public readonly architecture: Architecture;
/**
* The timeout configured for this lambda.
*/
public readonly timeout?: Duration;
public readonly permissionsNode = this.node;
protected readonly canCreatePermissions = true;
/** @internal */
public readonly _layers: ILayerVersion[] = [];
private _logGroup?: logs.ILogGroup;
/**
* Environment variables for this function
*/
private environment: { [key: string]: EnvironmentConfig } = {};
private readonly currentVersionOptions?: VersionOptions;
private _currentVersion?: Version;
private _architecture?: Architecture;
private hashMixins = new Array<string>();
constructor(scope: Construct, id: string, props: FunctionProps) {
super(scope, id, {
physicalName: props.functionName,
});
if (props.functionName && !Token.isUnresolved(props.functionName)) {
if (props.functionName.length > 64) {
throw new Error(`Function name can not be longer than 64 characters but has ${props.functionName.length} characters.`);
}
if (!/^[a-zA-Z0-9-_]+$/.test(props.functionName)) {
throw new Error(`Function name ${props.functionName} can contain only letters, numbers, hyphens, or underscores with no spaces.`);
}
}
if (props.description && !Token.isUnresolved(props.description)) {
if (props.description.length > 256) {
throw new Error(`Function description can not be longer than 256 characters but has ${props.description.length} characters.`);
}
}
const managedPolicies = new Array<iam.IManagedPolicy>();
// the arn is in the form of - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
managedPolicies.push(iam.ManagedPolicy.fromAwsManagedPolicyName('service-role/AWSLambdaBasicExecutionRole'));
if (props.vpc) {
// Policy that will have ENI creation permissions
managedPolicies.push(iam.ManagedPolicy.fromAwsManagedPolicyName('service-role/AWSLambdaVPCAccessExecutionRole'));
}
this.role = props.role || new iam.Role(this, 'ServiceRole', {
assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com'),
managedPolicies,
});
this.grantPrincipal = this.role;
// add additional managed policies when necessary
if (props.filesystem) {
const config = props.filesystem.config;
if (config.policies) {
config.policies.forEach(p => {
this.role?.addToPrincipalPolicy(p);
});
}
}
for (const statement of (props.initialPolicy || [])) {
this.role.addToPrincipalPolicy(statement);
}
const code = props.code.bind(this);
verifyCodeConfig(code, props);
let profilingGroupEnvironmentVariables: { [key: string]: string } = {};
if (props.profilingGroup && props.profiling !== false) {
this.validateProfiling(props);
props.profilingGroup.grantPublish(this.role);
profilingGroupEnvironmentVariables = {
AWS_CODEGURU_PROFILER_GROUP_NAME: props.profilingGroup.profilingGroupName,
AWS_CODEGURU_PROFILER_TARGET_REGION: props.profilingGroup.env.region,
AWS_CODEGURU_PROFILER_GROUP_ARN: props.profilingGroup.profilingGroupArn,
AWS_CODEGURU_PROFILER_ENABLED: 'TRUE',
};
} else if (props.profiling) {
this.validateProfiling(props);
const profilingGroup = new ProfilingGroup(this, 'ProfilingGroup', {
computePlatform: ComputePlatform.AWS_LAMBDA,
});
profilingGroup.grantPublish(this.role);
profilingGroupEnvironmentVariables = {
AWS_CODEGURU_PROFILER_GROUP_NAME: profilingGroup.profilingGroupName,
AWS_CODEGURU_PROFILER_TARGET_REGION: profilingGroup.env.region,
AWS_CODEGURU_PROFILER_GROUP_ARN: profilingGroup.profilingGroupArn,
AWS_CODEGURU_PROFILER_ENABLED: 'TRUE',
};
}
const env = { ...profilingGroupEnvironmentVariables, ...props.environment };
for (const [key, value] of Object.entries(env)) {
this.addEnvironment(key, value);
}
// DLQ can be either sns.ITopic or sqs.IQueue
const dlqTopicOrQueue = this.buildDeadLetterQueue(props);
if (dlqTopicOrQueue !== undefined) {
if (this.isQueue(dlqTopicOrQueue)) {
this.deadLetterQueue = dlqTopicOrQueue;
} else {
this.deadLetterTopic = dlqTopicOrQueue;
}
}
let fileSystemConfigs: CfnFunction.FileSystemConfigProperty[] | undefined = undefined;
if (props.filesystem) {
fileSystemConfigs = [{
arn: props.filesystem.config.arn,
localMountPath: props.filesystem.config.localMountPath,
}];
}
if (props.architecture && props.architectures !== undefined) {
throw new Error('Either architecture or architectures must be specified but not both.');
}
if (props.architectures && props.architectures.length > 1) {
throw new Error('Only one architecture must be specified.');
}
this._architecture = props.architecture ?? (props.architectures && props.architectures[0]);
if (props.ephemeralStorageSize && !props.ephemeralStorageSize.isUnresolved()
&& (props.ephemeralStorageSize.toMebibytes() < 512 || props.ephemeralStorageSize.toMebibytes() > 10240)) {
throw new Error(`Ephemeral storage size must be between 512 and 10240 MB, received ${props.ephemeralStorageSize}.`);
}
const resource: CfnFunction = new CfnFunction(this, 'Resource', {
functionName: this.physicalName,
description: props.description,
code: {
s3Bucket: code.s3Location && code.s3Location.bucketName,
s3Key: code.s3Location && code.s3Location.objectKey,
s3ObjectVersion: code.s3Location && code.s3Location.objectVersion,
zipFile: code.inlineCode,
imageUri: code.image?.imageUri,
},
layers: Lazy.list({ produce: () => this.renderLayers() }), // Evaluated on synthesis
handler: props.handler === Handler.FROM_IMAGE ? undefined : props.handler,
timeout: props.timeout && props.timeout.toSeconds(),
packageType: props.runtime === Runtime.FROM_IMAGE ? 'Image' : undefined,
runtime: props.runtime === Runtime.FROM_IMAGE ? undefined : props.runtime.name,