-
Notifications
You must be signed in to change notification settings - Fork 4k
/
project.ts
2455 lines (2193 loc) · 91.6 KB
/
project.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 { IArtifacts } from './artifacts';
import { BuildSpec } from './build-spec';
import { Cache } from './cache';
import { CodeBuildMetrics } from './codebuild-canned-metrics.generated';
import { CfnProject } from './codebuild.generated';
import { CodePipelineArtifacts } from './codepipeline-artifacts';
import { ComputeType } from './compute-type';
import { EnvironmentType } from './environment-type';
import { IFileSystemLocation } from './file-location';
import { IFleet } from './fleet';
import { LinuxArmLambdaBuildImage } from './linux-arm-lambda-build-image';
import { LinuxLambdaBuildImage } from './linux-lambda-build-image';
import { NoArtifacts } from './no-artifacts';
import { NoSource } from './no-source';
import { runScriptLinuxBuildSpec, S3_BUCKET_ENV, S3_KEY_ENV } from './private/run-script-linux-build-spec';
import { LoggingOptions } from './project-logs';
import { renderReportGroupArn } from './report-group-utils';
import { ISource } from './source';
import { CODEPIPELINE_SOURCE_ARTIFACTS_TYPE, NO_SOURCE_TYPE } from './source-types';
import * as cloudwatch from '../../aws-cloudwatch';
import * as notifications from '../../aws-codestarnotifications';
import * as ec2 from '../../aws-ec2';
import * as ecr from '../../aws-ecr';
import { DockerImageAsset, DockerImageAssetProps } from '../../aws-ecr-assets';
import * as events from '../../aws-events';
import * as iam from '../../aws-iam';
import * as kms from '../../aws-kms';
import * as s3 from '../../aws-s3';
import * as secretsmanager from '../../aws-secretsmanager';
import { ArnFormat, Aws, Duration, IResource, Lazy, Names, PhysicalName, Reference, Resource, SecretValue, Stack, Token, TokenComparison, Tokenization } from '../../core';
const VPC_POLICY_SYM = Symbol.for('@aws-cdk/aws-codebuild.roleVpcPolicy');
/**
* The type returned from `IProject#enableBatchBuilds`.
*/
export interface BatchBuildConfig {
/** The IAM batch service Role of this Project. */
readonly role: iam.IRole;
}
/**
* Location of a PEM certificate on S3
*/
export interface BuildEnvironmentCertificate {
/**
* The bucket where the certificate is
*/
readonly bucket: s3.IBucket;
/**
* The full path and name of the key file
*/
readonly objectKey: string;
}
/**
* Additional options to pass to the notification rule.
*/
export interface ProjectNotifyOnOptions extends notifications.NotificationRuleOptions {
/**
* A list of event types associated with this notification rule for CodeBuild Project.
* For a complete list of event types and IDs, see Notification concepts in the Developer Tools Console User Guide.
* @see https://docs.aws.amazon.com/dtconsole/latest/userguide/concepts.html#concepts-api
*/
readonly events: ProjectNotificationEvents[];
}
export interface IProject extends IResource, iam.IGrantable, ec2.IConnectable, notifications.INotificationRuleSource {
/**
* The ARN of this Project.
* @attribute
*/
readonly projectArn: string;
/**
* The human-visible name of this Project.
* @attribute
*/
readonly projectName: string;
/** The IAM service Role of this Project. Undefined for imported Projects. */
readonly role?: iam.IRole;
/**
* Enable batch builds.
*
* Returns an object contining the batch service role if batch builds
* could be enabled.
*/
enableBatchBuilds(): BatchBuildConfig | undefined;
addToRolePolicy(policyStatement: iam.PolicyStatement): void;
/**
* Defines a CloudWatch event rule triggered when something happens with this project.
*
* @see https://docs.aws.amazon.com/codebuild/latest/userguide/sample-build-notifications.html
*/
onEvent(id: string, options?: events.OnEventOptions): events.Rule;
/**
* Defines a CloudWatch event rule triggered when the build project state
* changes. You can filter specific build status events using an event
* pattern filter on the `build-status` detail field:
*
* const rule = project.onStateChange('OnBuildStarted', { target });
* rule.addEventPattern({
* detail: {
* 'build-status': [
* "IN_PROGRESS",
* "SUCCEEDED",
* "FAILED",
* "STOPPED"
* ]
* }
* });
*
* You can also use the methods `onBuildFailed` and `onBuildSucceeded` to define rules for
* these specific state changes.
*
* To access fields from the event in the event target input,
* use the static fields on the `StateChangeEvent` class.
*
* @see https://docs.aws.amazon.com/codebuild/latest/userguide/sample-build-notifications.html
*/
onStateChange(id: string, options?: events.OnEventOptions): events.Rule;
/**
* Defines a CloudWatch event rule that triggers upon phase change of this
* build project.
*
* @see https://docs.aws.amazon.com/codebuild/latest/userguide/sample-build-notifications.html
*/
onPhaseChange(id: string, options?: events.OnEventOptions): events.Rule;
/**
* Defines an event rule which triggers when a build starts.
*/
onBuildStarted(id: string, options?: events.OnEventOptions): events.Rule;
/**
* Defines an event rule which triggers when a build fails.
*/
onBuildFailed(id: string, options?: events.OnEventOptions): events.Rule;
/**
* Defines an event rule which triggers when a build completes successfully.
*/
onBuildSucceeded(id: string, options?: events.OnEventOptions): events.Rule;
/**
* @returns a CloudWatch metric associated with this build project.
* @param metricName The name of the metric
* @param props Customization properties
*/
metric(metricName: string, props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* Measures the number of builds triggered.
*
* Units: Count
*
* Valid CloudWatch statistics: Sum
*
* @default sum over 5 minutes
*/
metricBuilds(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* Measures the duration of all builds over time.
*
* Units: Seconds
*
* Valid CloudWatch statistics: Average (recommended), Maximum, Minimum
*
* @default average over 5 minutes
*/
metricDuration(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* Measures the number of successful builds.
*
* Units: Count
*
* Valid CloudWatch statistics: Sum
*
* @default sum over 5 minutes
*/
metricSucceededBuilds(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* Measures the number of builds that failed because of client error or
* because of a timeout.
*
* Units: Count
*
* Valid CloudWatch statistics: Sum
*
* @default sum over 5 minutes
*/
metricFailedBuilds(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* Defines a CodeStar Notification rule triggered when the project
* events emitted by you specified, it very similar to `onEvent` API.
*
* You can also use the methods `notifyOnBuildSucceeded` and
* `notifyOnBuildFailed` to define rules for these specific event emitted.
*
* @param id The logical identifier of the CodeStar Notifications rule that will be created
* @param target The target to register for the CodeStar Notifications destination.
* @param options Customization options for CodeStar Notifications rule
* @returns CodeStar Notifications rule associated with this build project.
*/
notifyOn(
id: string,
target: notifications.INotificationRuleTarget,
options: ProjectNotifyOnOptions,
): notifications.INotificationRule;
/**
* Defines a CodeStar notification rule which triggers when a build completes successfully.
*/
notifyOnBuildSucceeded(
id: string,
target: notifications.INotificationRuleTarget,
options?: notifications.NotificationRuleOptions,
): notifications.INotificationRule;
/**
* Defines a CodeStar notification rule which triggers when a build fails.
*/
notifyOnBuildFailed(
id: string,
target: notifications.INotificationRuleTarget,
options?: notifications.NotificationRuleOptions,
): notifications.INotificationRule;
}
/**
* Represents a reference to a CodeBuild Project.
*
* If you're managing the Project alongside the rest of your CDK resources,
* use the `Project` class.
*
* If you want to reference an already existing Project
* (or one defined in a different CDK Stack),
* use the `import` method.
*/
abstract class ProjectBase extends Resource implements IProject {
public abstract readonly grantPrincipal: iam.IPrincipal;
/** The ARN of this Project. */
public abstract readonly projectArn: string;
/** The human-visible name of this Project. */
public abstract readonly projectName: string;
/** The IAM service Role of this Project. */
public abstract readonly role?: iam.IRole;
/**
* Actual connections object for this Project.
* May be unset, in which case this Project is not configured to use a VPC.
* @internal
*/
protected _connections: ec2.Connections | undefined;
/**
* Access the Connections object.
* Will fail if this Project does not have a VPC set.
*/
public get connections(): ec2.Connections {
if (!this._connections) {
throw new Error('Only VPC-associated Projects have security groups to manage. Supply the "vpc" parameter when creating the Project');
}
return this._connections;
}
public enableBatchBuilds(): BatchBuildConfig | undefined {
return undefined;
}
/**
* Add a permission only if there's a policy attached.
* @param statement The permissions statement to add
*/
public addToRolePolicy(statement: iam.PolicyStatement) {
if (this.role) {
this.role.addToPrincipalPolicy(statement);
}
}
/**
* Defines a CloudWatch event rule triggered when something happens with this project.
*
* @see https://docs.aws.amazon.com/codebuild/latest/userguide/sample-build-notifications.html
*/
public onEvent(id: string, options: events.OnEventOptions = {}): events.Rule {
const rule = new events.Rule(this, id, options);
rule.addTarget(options.target);
rule.addEventPattern({
source: ['aws.codebuild'],
detail: {
'project-name': [this.projectName],
},
});
return rule;
}
/**
* Defines a CloudWatch event rule triggered when the build project state
* changes. You can filter specific build status events using an event
* pattern filter on the `build-status` detail field:
*
* const rule = project.onStateChange('OnBuildStarted', { target });
* rule.addEventPattern({
* detail: {
* 'build-status': [
* "IN_PROGRESS",
* "SUCCEEDED",
* "FAILED",
* "STOPPED"
* ]
* }
* });
*
* You can also use the methods `onBuildFailed` and `onBuildSucceeded` to define rules for
* these specific state changes.
*
* To access fields from the event in the event target input,
* use the static fields on the `StateChangeEvent` class.
*
* @see https://docs.aws.amazon.com/codebuild/latest/userguide/sample-build-notifications.html
*/
public onStateChange(id: string, options: events.OnEventOptions = {}) {
const rule = this.onEvent(id, options);
rule.addEventPattern({
detailType: ['CodeBuild Build State Change'],
});
return rule;
}
/**
* Defines a CloudWatch event rule that triggers upon phase change of this
* build project.
*
* @see https://docs.aws.amazon.com/codebuild/latest/userguide/sample-build-notifications.html
*/
public onPhaseChange(id: string, options: events.OnEventOptions = {}) {
const rule = this.onEvent(id, options);
rule.addEventPattern({
detailType: ['CodeBuild Build Phase Change'],
});
return rule;
}
/**
* Defines an event rule which triggers when a build starts.
*
* To access fields from the event in the event target input,
* use the static fields on the `StateChangeEvent` class.
*/
public onBuildStarted(id: string, options: events.OnEventOptions = {}) {
const rule = this.onStateChange(id, options);
rule.addEventPattern({
detail: {
'build-status': ['IN_PROGRESS'],
},
});
return rule;
}
/**
* Defines an event rule which triggers when a build fails.
*
* To access fields from the event in the event target input,
* use the static fields on the `StateChangeEvent` class.
*/
public onBuildFailed(id: string, options: events.OnEventOptions = {}) {
const rule = this.onStateChange(id, options);
rule.addEventPattern({
detail: {
'build-status': ['FAILED'],
},
});
return rule;
}
/**
* Defines an event rule which triggers when a build completes successfully.
*
* To access fields from the event in the event target input,
* use the static fields on the `StateChangeEvent` class.
*/
public onBuildSucceeded(id: string, options: events.OnEventOptions = {}) {
const rule = this.onStateChange(id, options);
rule.addEventPattern({
detail: {
'build-status': ['SUCCEEDED'],
},
});
return rule;
}
/**
* @returns a CloudWatch metric associated with this build project.
* @param metricName The name of the metric
* @param props Customization properties
*/
public metric(metricName: string, props?: cloudwatch.MetricOptions) {
return new cloudwatch.Metric({
namespace: 'AWS/CodeBuild',
metricName,
dimensionsMap: { ProjectName: this.projectName },
...props,
}).attachTo(this);
}
/**
* Measures the number of builds triggered.
*
* Units: Count
*
* Valid CloudWatch statistics: Sum
*
* @default sum over 5 minutes
*/
public metricBuilds(props?: cloudwatch.MetricOptions): cloudwatch.Metric {
return this.cannedMetric(CodeBuildMetrics.buildsSum, props);
}
/**
* Measures the duration of all builds over time.
*
* Units: Seconds
*
* Valid CloudWatch statistics: Average (recommended), Maximum, Minimum
*
* @default average over 5 minutes
*/
public metricDuration(props?: cloudwatch.MetricOptions): cloudwatch.Metric {
return this.cannedMetric(CodeBuildMetrics.durationAverage, props);
}
/**
* Measures the number of successful builds.
*
* Units: Count
*
* Valid CloudWatch statistics: Sum
*
* @default sum over 5 minutes
*/
public metricSucceededBuilds(props?: cloudwatch.MetricOptions): cloudwatch.Metric {
return this.cannedMetric(CodeBuildMetrics.succeededBuildsSum, props);
}
/**
* Measures the number of builds that failed because of client error or
* because of a timeout.
*
* Units: Count
*
* Valid CloudWatch statistics: Sum
*
* @default sum over 5 minutes
*/
public metricFailedBuilds(props?: cloudwatch.MetricOptions): cloudwatch.Metric {
return this.cannedMetric(CodeBuildMetrics.failedBuildsSum, props);
}
public notifyOn(
id: string,
target: notifications.INotificationRuleTarget,
options: ProjectNotifyOnOptions,
): notifications.INotificationRule {
return new notifications.NotificationRule(this, id, {
...options,
source: this,
targets: [target],
});
}
public notifyOnBuildSucceeded(
id: string,
target: notifications.INotificationRuleTarget,
options?: notifications.NotificationRuleOptions,
): notifications.INotificationRule {
return this.notifyOn(id, target, {
...options,
events: [ProjectNotificationEvents.BUILD_SUCCEEDED],
});
}
public notifyOnBuildFailed(
id: string,
target: notifications.INotificationRuleTarget,
options?: notifications.NotificationRuleOptions,
): notifications.INotificationRule {
return this.notifyOn(id, target, {
...options,
events: [ProjectNotificationEvents.BUILD_FAILED],
});
}
public bindAsNotificationRuleSource(_scope: Construct): notifications.NotificationRuleSourceConfig {
return {
sourceArn: this.projectArn,
};
}
private cannedMetric(
fn: (dims: { ProjectName: string }) => cloudwatch.MetricProps,
props?: cloudwatch.MetricOptions): cloudwatch.Metric {
return new cloudwatch.Metric({
...fn({ ProjectName: this.projectName }),
...props,
}).attachTo(this);
}
}
export interface CommonProjectProps {
/**
* A description of the project. Use the description to identify the purpose
* of the project.
*
* @default - No description.
*/
readonly description?: string;
/**
* Filename or contents of buildspec in JSON format.
* @see https://docs.aws.amazon.com/codebuild/latest/userguide/build-spec-ref.html#build-spec-ref-example
*
* @default - Empty buildspec.
*/
readonly buildSpec?: BuildSpec;
/**
* Service Role to assume while running the build.
*
* @default - A role will be created.
*/
readonly role?: iam.IRole;
/**
* Encryption key to use to read and write artifacts.
*
* @default - The AWS-managed CMK for Amazon Simple Storage Service (Amazon S3) is used.
*/
readonly encryptionKey?: kms.IKey;
/**
* Caching strategy to use.
*
* @default Cache.none
*/
readonly cache?: Cache;
/**
* Build environment to use for the build.
*
* @default BuildEnvironment.LinuxBuildImage.STANDARD_7_0
*/
readonly environment?: BuildEnvironment;
/**
* Indicates whether AWS CodeBuild generates a publicly accessible URL for
* your project's build badge. For more information, see Build Badges Sample
* in the AWS CodeBuild User Guide.
*
* @default false
*/
readonly badge?: boolean;
/**
* The number of minutes after which AWS CodeBuild stops the build if it's
* not complete. For valid values, see the timeoutInMinutes field in the AWS
* CodeBuild User Guide.
*
* @default Duration.hours(1)
*/
readonly timeout?: Duration;
/**
* Additional environment variables to add to the build environment.
*
* @default - No additional environment variables are specified.
*/
readonly environmentVariables?: { [name: string]: BuildEnvironmentVariable };
/**
* Whether to check for the presence of any secrets in the environment variables of the default type, BuildEnvironmentVariableType.PLAINTEXT.
* Since using a secret for the value of that kind of variable would result in it being displayed in plain text in the AWS Console,
* the construct will throw an exception if it detects a secret was passed there.
* Pass this property as false if you want to skip this validation,
* and keep using a secret in a plain text environment variable.
*
* @default true
*/
readonly checkSecretsInPlainTextEnvVariables?: boolean;
/**
* The physical, human-readable name of the CodeBuild Project.
*
* @default - Name is automatically generated.
*/
readonly projectName?: string;
/**
* VPC network to place codebuild network interfaces
*
* Specify this if the codebuild project needs to access resources in a VPC.
*
* @default - No VPC is specified.
*/
readonly vpc?: ec2.IVpc;
/**
* Where to place the network interfaces within the VPC.
*
* To access AWS services, your CodeBuild project needs to be in one of the following types of subnets:
*
* 1. Subnets with access to the internet (of type PRIVATE_WITH_EGRESS).
* 2. Private subnets unconnected to the internet, but with [VPC endpoints](https://docs.aws.amazon.com/codebuild/latest/userguide/use-vpc-endpoints-with-codebuild.html) for the necessary services.
*
* If you don't specify a subnet selection, the default behavior is to use PRIVATE_WITH_EGRESS subnets first if they exist,
* then PRIVATE_WITHOUT_EGRESS, and finally PUBLIC subnets. If your VPC doesn't have PRIVATE_WITH_EGRESS subnets but you need
* AWS service access, add VPC Endpoints to your private subnets.
*
* @see https://docs.aws.amazon.com/codebuild/latest/userguide/vpc-support.html
*
* @default - private subnets if available else public subnets
*/
readonly subnetSelection?: ec2.SubnetSelection;
/**
* What security group to associate with the codebuild project's network interfaces.
* If no security group is identified, one will be created automatically.
*
* Only used if 'vpc' is supplied.
*
* @default - Security group will be automatically created.
*
*/
readonly securityGroups?: ec2.ISecurityGroup[];
/**
* Whether to allow the CodeBuild to send all network traffic
*
* If set to false, you must individually add traffic rules to allow the
* CodeBuild project to connect to network targets.
*
* Only used if 'vpc' is supplied.
*
* @default true
*/
readonly allowAllOutbound?: boolean;
/**
* An ProjectFileSystemLocation objects for a CodeBuild build project.
*
* A ProjectFileSystemLocation object specifies the identifier, location, mountOptions, mountPoint,
* and type of a file system created using Amazon Elastic File System.
*
* @default - no file system locations
*/
readonly fileSystemLocations?: IFileSystemLocation[];
/**
* Add permissions to this project's role to create and use test report groups with name starting with the name of this project.
*
* That is the standard report group that gets created when a simple name
* (in contrast to an ARN)
* is used in the 'reports' section of the buildspec of this project.
* This is usually harmless, but you can turn these off if you don't plan on using test
* reports in this project.
*
* @default true
*
* @see https://docs.aws.amazon.com/codebuild/latest/userguide/test-report-group-naming.html
*/
readonly grantReportGroupPermissions?: boolean;
/**
* Information about logs for the build project. A project can create logs in Amazon CloudWatch Logs, an S3 bucket, or both.
*
* @default - no log configuration is set
*/
readonly logging?: LoggingOptions;
/**
* The number of minutes after which AWS CodeBuild stops the build if it's
* still in queue. For valid values, see the timeoutInMinutes field in the AWS
* CodeBuild User Guide.
*
* @default - no queue timeout is set
*/
readonly queuedTimeout?: Duration;
/**
* Maximum number of concurrent builds. Minimum value is 1 and maximum is account build limit.
*
* @default - no explicit limit is set
*/
readonly concurrentBuildLimit?: number;
/**
* Add the permissions necessary for debugging builds with SSM Session Manager
*
* If the following prerequisites have been met:
*
* - The necessary permissions have been added by setting this flag to true.
* - The build image has the SSM agent installed (true for default CodeBuild images).
* - The build is started with [debugSessionEnabled](https://docs.aws.amazon.com/codebuild/latest/APIReference/API_StartBuild.html#CodeBuild-StartBuild-request-debugSessionEnabled) set to true.
*
* Then the build container can be paused and inspected using Session Manager
* by invoking the `codebuild-breakpoint` command somewhere during the build.
*
* `codebuild-breakpoint` commands will be ignored if the build is not started
* with `debugSessionEnabled=true`.
*
* @see https://docs.aws.amazon.com/codebuild/latest/userguide/session-manager.html
* @default false
*/
readonly ssmSessionPermissions?: boolean;
/**
* Specifies the visibility of the project's builds.
*
* @default - no visibility is set
*/
readonly visibility?: ProjectVisibility;
/**
* CodeBuild will automatically call retry build using the project's service role up to the auto-retry limit.
* `autoRetryLimit` must be between 0 and 10.
*
* @default - no retry
*/
readonly autoRetryLimit?: number;
}
export interface ProjectProps extends CommonProjectProps {
/**
* The source of the build.
* *Note*: if `NoSource` is given as the source,
* then you need to provide an explicit `buildSpec`.
*
* @default - NoSource
*/
readonly source?: ISource;
/**
* Defines where build artifacts will be stored.
* Could be: PipelineBuildArtifacts, NoArtifacts and S3Artifacts.
*
* @default NoArtifacts
*/
readonly artifacts?: IArtifacts;
/**
* The secondary sources for the Project.
* Can be also added after the Project has been created by using the `Project#addSecondarySource` method.
*
* @default - No secondary sources.
* @see https://docs.aws.amazon.com/codebuild/latest/userguide/sample-multi-in-out.html
*/
readonly secondarySources?: ISource[];
/**
* The secondary artifacts for the Project.
* Can also be added after the Project has been created by using the `Project#addSecondaryArtifact` method.
*
* @default - No secondary artifacts.
* @see https://docs.aws.amazon.com/codebuild/latest/userguide/sample-multi-in-out.html
*/
readonly secondaryArtifacts?: IArtifacts[];
}
/**
* The extra options passed to the `IProject.bindToCodePipeline` method.
*/
export interface BindToCodePipelineOptions {
/**
* The artifact bucket that will be used by the action that invokes this project.
*/
readonly artifactBucket: s3.IBucket;
}
/**
* A representation of a CodeBuild Project.
*/
export class Project extends ProjectBase {
public static fromProjectArn(scope: Construct, id: string, projectArn: string): IProject {
const parsedArn = Stack.of(scope).splitArn(projectArn, ArnFormat.SLASH_RESOURCE_NAME);
class Import extends ProjectBase {
public readonly grantPrincipal: iam.IPrincipal;
public readonly projectArn = projectArn;
public readonly projectName = parsedArn.resourceName!;
public readonly role?: iam.Role = undefined;
constructor(s: Construct, i: string) {
super(s, i, {
account: parsedArn.account,
region: parsedArn.region,
});
this.grantPrincipal = new iam.UnknownPrincipal({ resource: this });
}
}
return new Import(scope, id);
}
/**
* Import a Project defined either outside the CDK,
* or in a different CDK Stack
* (and exported using the `export` method).
*
* @note if you're importing a CodeBuild Project for use
* in a CodePipeline, make sure the existing Project
* has permissions to access the S3 Bucket of that Pipeline -
* otherwise, builds in that Pipeline will always fail.
*
* @param scope the parent Construct for this Construct
* @param id the logical name of this Construct
* @param projectName the name of the project to import
* @returns a reference to the existing Project
*/
public static fromProjectName(scope: Construct, id: string, projectName: string): IProject {
class Import extends ProjectBase {
public readonly grantPrincipal: iam.IPrincipal;
public readonly projectArn: string;
public readonly projectName: string;
public readonly role?: iam.Role = undefined;
constructor(s: Construct, i: string) {
super(s, i);
this.projectArn = Stack.of(this).formatArn({
service: 'codebuild',
resource: 'project',
resourceName: projectName,
});
this.grantPrincipal = new iam.UnknownPrincipal({ resource: this });
this.projectName = projectName;
}
}
return new Import(scope, id);
}
/**
* Convert the environment variables map of string to `BuildEnvironmentVariable`,
* which is the customer-facing type, to a list of `CfnProject.EnvironmentVariableProperty`,
* which is the representation of environment variables in CloudFormation.
*
* @param environmentVariables the map of string to environment variables
* @param validateNoPlainTextSecrets whether to throw an exception
* if any of the plain text environment variables contain secrets, defaults to 'false'
* @returns an array of `CfnProject.EnvironmentVariableProperty` instances
*/
public static serializeEnvVariables(environmentVariables: { [name: string]: BuildEnvironmentVariable },
validateNoPlainTextSecrets: boolean = false, principal?: iam.IGrantable): CfnProject.EnvironmentVariableProperty[] {
const ret = new Array<CfnProject.EnvironmentVariableProperty>();
const ssmIamResources = new Array<string>();
const secretsManagerIamResources = new Set<string>();
const kmsIamResources = new Set<string>();
for (const [name, envVariable] of Object.entries(environmentVariables)) {
const envVariableValue = envVariable.value?.toString();
const cfnEnvVariable: CfnProject.EnvironmentVariableProperty = {
name,
type: envVariable.type || BuildEnvironmentVariableType.PLAINTEXT,
value: envVariableValue,
};
ret.push(cfnEnvVariable);
// validate that the plain-text environment variables don't contain any secrets in them
if (validateNoPlainTextSecrets && cfnEnvVariable.type === BuildEnvironmentVariableType.PLAINTEXT) {
const fragments = Tokenization.reverseString(cfnEnvVariable.value);
for (const token of fragments.tokens) {
if (token instanceof SecretValue) {
throw new Error(`Plaintext environment variable '${name}' contains a secret value! ` +
'This means the value of this variable will be visible in plain text in the AWS Console. ' +
"Please consider using CodeBuild's SecretsManager environment variables feature instead. " +
"If you'd like to continue with having this secret in the plaintext environment variables, " +
'please set the checkSecretsInPlainTextEnvVariables property to false');
}
}
}
if (principal) {
const stack = Stack.of(principal as unknown as IConstruct);
// save the SSM env variables
if (envVariable.type === BuildEnvironmentVariableType.PARAMETER_STORE) {
ssmIamResources.push(stack.formatArn({
service: 'ssm',
resource: 'parameter',
// If the parameter name starts with / the resource name is not separated with a double '/'
// arn:aws:ssm:region:1111111111:parameter/PARAM_NAME
resourceName: envVariableValue.startsWith('/')
? envVariableValue.slice(1)
: envVariableValue,
}));
}
// save SecretsManager env variables
if (envVariable.type === BuildEnvironmentVariableType.SECRETS_MANAGER) {
// We have 3 basic cases here of what envVariableValue can be:
// 1. A string that starts with 'arn:' (and might contain Token fragments).
// 2. A Token.
// 3. A simple value, like 'secret-id'.
if (envVariableValue.startsWith('arn:')) {
const parsedArn = stack.splitArn(envVariableValue, ArnFormat.COLON_RESOURCE_NAME);
if (!parsedArn.resourceName) {
throw new Error('SecretManager ARN is missing the name of the secret: ' + envVariableValue);
}
// the value of the property can be a complex string, separated by ':';
// see https://docs.aws.amazon.com/codebuild/latest/userguide/build-spec-ref.html#build-spec.env.secrets-manager
const secretName = parsedArn.resourceName.split(':')[0];
secretsManagerIamResources.add(stack.formatArn({
service: 'secretsmanager',
resource: 'secret',
// since we don't know whether the ARN was full, or partial
// (CodeBuild supports both),
// stick a "*" at the end, which makes it work for both
resourceName: `${secretName}*`,
arnFormat: ArnFormat.COLON_RESOURCE_NAME,
partition: parsedArn.partition,
account: parsedArn.account,
region: parsedArn.region,
}));
// if secret comes from another account, SecretsManager will need to access
// KMS on the other account as well to be able to get the secret
if (parsedArn.account && Token.compareStrings(parsedArn.account, stack.account) === TokenComparison.DIFFERENT) {
kmsIamResources.add(stack.formatArn({
service: 'kms',
resource: 'key',
// We do not know the ID of the key, but since this is a cross-account access,
// the key policies have to allow this access, so a wildcard is safe here
resourceName: '*',
arnFormat: ArnFormat.SLASH_RESOURCE_NAME,
partition: parsedArn.partition,
account: parsedArn.account,
region: parsedArn.region,
}));
}
} else if (Token.isUnresolved(envVariableValue)) {
// the value of the property can be a complex string, separated by ':';
// see https://docs.aws.amazon.com/codebuild/latest/userguide/build-spec-ref.html#build-spec.env.secrets-manager
let secretArn = envVariableValue.split(':')[0];
// parse the Token, and see if it represents a single resource
// (we will assume it's a Secret from SecretsManager)
const fragments = Tokenization.reverseString(envVariableValue);
if (fragments.tokens.length === 1) {
const resolvable = fragments.tokens[0];
if (Reference.isReference(resolvable)) {
// check the Stack the resource owning the reference belongs to
const resourceStack = Stack.of(resolvable.target);
if (Token.compareStrings(stack.account, resourceStack.account) === TokenComparison.DIFFERENT) {
// since this is a cross-account access,
// add the appropriate KMS permissions
kmsIamResources.add(stack.formatArn({
service: 'kms',
resource: 'key',
// We do not know the ID of the key, but since this is a cross-account access,
// the key policies have to allow this access, so a wildcard is safe here
resourceName: '*',
arnFormat: ArnFormat.SLASH_RESOURCE_NAME,
partition: resourceStack.partition,
account: resourceStack.account,
region: resourceStack.region,
}));
// Work around a bug in SecretsManager -
// when the access is cross-environment,
// Secret.secretArn returns a partial ARN!
// So add a "*" at the end, so that the permissions work
secretArn = `${secretArn}-??????`;
}
}
}
// if we are passed a Token, we should assume it's the ARN of the Secret
// (as the name would not work anyway, because it would be the full name, which CodeBuild does not support)
secretsManagerIamResources.add(secretArn);
} else {
// the value of the property can be a complex string, separated by ':';
// see https://docs.aws.amazon.com/codebuild/latest/userguide/build-spec-ref.html#build-spec.env.secrets-manager
const secretName = envVariableValue.split(':')[0];