-
Notifications
You must be signed in to change notification settings - Fork 4.1k
/
Copy pathproject.ts
1188 lines (1048 loc) · 38 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 assets = require('@aws-cdk/assets');
import { DockerImageAsset, DockerImageAssetProps } from '@aws-cdk/assets-docker';
import cloudwatch = require('@aws-cdk/aws-cloudwatch');
import ecr = require('@aws-cdk/aws-ecr');
import events = require('@aws-cdk/aws-events');
import iam = require('@aws-cdk/aws-iam');
import kms = require('@aws-cdk/aws-kms');
import s3 = require('@aws-cdk/aws-s3');
import cdk = require('@aws-cdk/cdk');
import { BuildArtifacts, CodePipelineBuildArtifacts, NoBuildArtifacts } from './artifacts';
import { CfnProject } from './codebuild.generated';
import {
CommonPipelineBuildActionProps, CommonPipelineTestActionProps,
PipelineBuildAction, PipelineTestAction
} from './pipeline-actions';
import { BuildSource, NoSource, SourceType } from './source';
const CODEPIPELINE_TYPE = 'CODEPIPELINE';
const S3_BUCKET_ENV = 'SCRIPT_S3_BUCKET';
const S3_KEY_ENV = 'SCRIPT_S3_KEY';
export interface IProject extends cdk.IConstruct, events.IEventRuleTarget {
/** The ARN of this Project. */
readonly projectArn: string;
/** The human-visible name of this Project. */
readonly projectName: string;
/** The IAM service Role of this Project. Undefined for imported Projects. */
readonly role?: iam.IRole;
/**
* Convenience method for creating a new {@link PipelineBuildAction CodeBuild build Action}.
*
* @param props the construction properties of the new Action
* @returns the newly created {@link PipelineBuildAction CodeBuild build Action}
*/
toCodePipelineBuildAction(props: CommonPipelineBuildActionProps): PipelineBuildAction;
/**
* Convenience method for creating a new {@link PipelineTestAction CodeBuild test Action}.
*
* @param props the construction properties of the new Action
* @returns the newly created {@link PipelineTestAction CodeBuild test Action}
*/
toCodePipelineTestAction(props: CommonPipelineTestActionProps): PipelineTestAction;
/**
* 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.
*
* @see https://docs.aws.amazon.com/codebuild/latest/userguide/sample-build-notifications.html
*/
onStateChange(name: string, target?: events.IEventRuleTarget, options?: events.EventRuleProps): events.EventRule;
/**
* 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(name: string, target?: events.IEventRuleTarget, options?: events.EventRuleProps): events.EventRule;
/**
* Defines an event rule which triggers when a build starts.
*/
onBuildStarted(name: string, target?: events.IEventRuleTarget, options?: events.EventRuleProps): events.EventRule;
/**
* Defines an event rule which triggers when a build fails.
*/
onBuildFailed(name: string, target?: events.IEventRuleTarget, options?: events.EventRuleProps): events.EventRule;
/**
* Defines an event rule which triggers when a build completes successfully.
*/
onBuildSucceeded(name: string, target?: events.IEventRuleTarget, options?: events.EventRuleProps): events.EventRule;
/**
* @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.MetricCustomization): cloudwatch.Metric;
/**
* Measures the number of builds triggered.
*
* Units: Count
*
* Valid CloudWatch statistics: Sum
*
* @default sum over 5 minutes
*/
metricBuilds(props?: cloudwatch.MetricCustomization): 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.MetricCustomization): cloudwatch.Metric;
/**
* Measures the number of successful builds.
*
* Units: Count
*
* Valid CloudWatch statistics: Sum
*
* @default sum over 5 minutes
*/
metricSucceededBuilds(props?: cloudwatch.MetricCustomization): 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.MetricCustomization): cloudwatch.Metric;
/**
* Export this Project. Allows referencing this Project in a different CDK Stack.
*/
export(): ProjectImportProps;
}
/**
* Properties of a reference to a CodeBuild Project.
*
* @see Project.import
* @see Project.export
*/
export interface ProjectImportProps {
/**
* The human-readable name of the CodeBuild Project we're referencing.
* The Project must be in the same account and region as the root Stack.
*/
projectName: string;
}
/**
* Represents a reference to a CodeBuild Project.
*
* If you're managing the Project alongside the rest of your CDK resources,
* use the {@link Project} class.
*
* If you want to reference an already existing Project
* (or one defined in a different CDK Stack),
* use the {@link import} method.
*/
export abstract class ProjectBase extends cdk.Construct implements IProject {
/** 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. Undefined for imported Projects. */
public abstract readonly role?: iam.IRole;
/** A role used by CloudWatch events to trigger a build */
private eventsRole?: iam.Role;
public abstract export(): ProjectImportProps;
public toCodePipelineBuildAction(props: CommonPipelineBuildActionProps): PipelineBuildAction {
return new PipelineBuildAction({
...props,
project: this,
});
}
public toCodePipelineTestAction(props: CommonPipelineTestActionProps): PipelineTestAction {
return new PipelineTestAction({
...props,
project: this,
});
}
/**
* 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.
*
* @see https://docs.aws.amazon.com/codebuild/latest/userguide/sample-build-notifications.html
*/
public onStateChange(name: string, target?: events.IEventRuleTarget, options?: events.EventRuleProps) {
const rule = new events.EventRule(this, name, options);
rule.addTarget(target);
rule.addEventPattern({
source: [ 'aws.codebuild' ],
detailType: [ 'CodeBuild Build State Change' ],
detail: {
'project-name': [
this.projectName
]
}
});
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(name: string, target?: events.IEventRuleTarget, options?: events.EventRuleProps) {
const rule = new events.EventRule(this, name, options);
rule.addTarget(target);
rule.addEventPattern({
source: [ 'aws.codebuild' ],
detailType: [ 'CodeBuild Build Phase Change' ],
detail: {
'project-name': [
this.projectName
]
}
});
return rule;
}
/**
* Defines an event rule which triggers when a build starts.
*/
public onBuildStarted(name: string, target?: events.IEventRuleTarget, options?: events.EventRuleProps) {
const rule = this.onStateChange(name, target, options);
rule.addEventPattern({
detail: {
'build-status': [ 'IN_PROGRESS' ]
}
});
return rule;
}
/**
* Defines an event rule which triggers when a build fails.
*/
public onBuildFailed(name: string, target?: events.IEventRuleTarget, options?: events.EventRuleProps) {
const rule = this.onStateChange(name, target, options);
rule.addEventPattern({
detail: {
'build-status': [ 'FAILED' ]
}
});
return rule;
}
/**
* Defines an event rule which triggers when a build completes successfully.
*/
public onBuildSucceeded(name: string, target?: events.IEventRuleTarget, options?: events.EventRuleProps) {
const rule = this.onStateChange(name, target, 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.MetricCustomization) {
return new cloudwatch.Metric({
namespace: 'AWS/CodeBuild',
metricName,
dimensions: { ProjectName: this.projectName },
...props
});
}
/**
* Measures the number of builds triggered.
*
* Units: Count
*
* Valid CloudWatch statistics: Sum
*
* @default sum over 5 minutes
*/
public metricBuilds(props?: cloudwatch.MetricCustomization) {
return this.metric('Builds', {
statistic: 'sum',
...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.MetricCustomization) {
return this.metric('Duration', {
statistic: 'avg',
...props
});
}
/**
* Measures the number of successful builds.
*
* Units: Count
*
* Valid CloudWatch statistics: Sum
*
* @default sum over 5 minutes
*/
public metricSucceededBuilds(props?: cloudwatch.MetricCustomization) {
return this.metric('SucceededBuilds', {
statistic: 'sum',
...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.MetricCustomization) {
return this.metric('FailedBuilds', {
statistic: 'sum',
...props,
});
}
/**
* Allows using build projects as event rule targets.
*/
public asEventRuleTarget(_ruleArn: string, _ruleId: string): events.EventRuleTargetProps {
if (!this.eventsRole) {
this.eventsRole = new iam.Role(this, 'EventsRole', {
assumedBy: new iam.ServicePrincipal('events.amazonaws.com')
});
this.eventsRole.addToPolicy(new iam.PolicyStatement()
.addAction('codebuild:StartBuild')
.addResource(this.projectArn));
}
return {
id: this.node.id,
arn: this.projectArn,
roleArn: this.eventsRole.roleArn,
};
}
}
class ImportedProject extends ProjectBase {
public readonly projectArn: string;
public readonly projectName: string;
public readonly role?: iam.Role = undefined;
constructor(scope: cdk.Construct, id: string, private readonly props: ProjectImportProps) {
super(scope, id);
this.projectArn = this.node.stack.formatArn({
service: 'codebuild',
resource: 'project',
resourceName: props.projectName,
});
this.projectName = props.projectName;
}
public export() {
return this.props;
}
}
export interface CommonProjectProps {
/**
* A description of the project. Use the description to identify the purpose
* of the project.
*/
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
*/
buildSpec?: any;
/**
* Run a script from an asset as build script
*
* If supplied together with buildSpec, the asset script will be run
* _after_ the existing commands in buildspec.
*
* This feature can also be used without a source, to simply run an
* arbitrary script in a serverless way.
*
* @default No asset build script
*/
buildScriptAsset?: assets.Asset;
/**
* The script in the asset to run.
*
* @default build.sh
*/
buildScriptAssetEntrypoint?: string;
/**
* Service Role to assume while running the build.
* If not specified, a role will be created.
*/
role?: iam.IRole;
/**
* Encryption key to use to read and write artifacts
* If not specified, a role will be created.
*/
encryptionKey?: kms.IEncryptionKey;
/**
* Bucket to store cached source artifacts
* If not specified, source artifacts will not be cached.
*/
cacheBucket?: s3.IBucket;
/**
* Subdirectory to store cached artifacts
*/
cacheDir?: string;
/**
* Build environment to use for the build.
*/
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.
*/
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.
*/
timeout?: number;
/**
* Additional environment variables to add to the build environment.
*/
environmentVariables?: { [name: string]: BuildEnvironmentVariable };
/**
* The physical, human-readable name of the CodeBuild Project.
*/
projectName?: string;
}
export interface ProjectProps extends CommonProjectProps {
/**
* The source of the build.
* *Note*: if {@link NoSource} is given as the source,
* then you need to provide an explicit `buildSpec`.
*
* @default NoSource
*/
source?: BuildSource;
/**
* Defines where build artifacts will be stored.
* Could be: PipelineBuildArtifacts, NoBuildArtifacts and S3BucketBuildArtifacts.
*
* @default NoBuildArtifacts
*/
artifacts?: BuildArtifacts;
/**
* The secondary sources for the Project.
* Can be also added after the Project has been created by using the {@link Project#addSecondarySource} method.
*
* @default []
* @see https://docs.aws.amazon.com/codebuild/latest/userguide/sample-multi-in-out.html
*/
secondarySources?: BuildSource[];
/**
* The secondary artifacts for the Project.
* Can also be added after the Project has been created by using the {@link Project#addSecondaryArtifact} method.
*
* @default []
* @see https://docs.aws.amazon.com/codebuild/latest/userguide/sample-multi-in-out.html
*/
secondaryArtifacts?: BuildArtifacts[];
}
/**
* A representation of a CodeBuild Project.
*/
export class Project extends ProjectBase {
/**
* Import a Project defined either outside the CDK,
* or in a different CDK Stack
* (and exported using the {@link 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 parent the parent Construct for this Construct
* @param name the logical name of this Construct
* @param props the properties of the referenced Project
* @returns a reference to the existing Project
*/
public static import(scope: cdk.Construct, id: string, props: ProjectImportProps): IProject {
return new ImportedProject(scope, id, props);
}
/**
* The IAM role for this project.
*/
public readonly role?: iam.IRole;
/**
* The ARN of the project.
*/
public readonly projectArn: string;
/**
* The name of the project.
*/
public readonly projectName: string;
private readonly source: BuildSource;
private readonly buildImage: IBuildImage;
private readonly _secondarySources: BuildSource[];
private readonly _secondaryArtifacts: BuildArtifacts[];
constructor(scope: cdk.Construct, id: string, props: ProjectProps) {
super(scope, id);
if (props.buildScriptAssetEntrypoint && !props.buildScriptAsset) {
throw new Error('To use buildScriptAssetEntrypoint, supply buildScriptAsset as well.');
}
this.role = props.role || new iam.Role(this, 'Role', {
assumedBy: new iam.ServicePrincipal('codebuild.amazonaws.com')
});
let cache: CfnProject.ProjectCacheProperty | undefined;
if (props.cacheBucket) {
const cacheDir = props.cacheDir != null ? props.cacheDir : new cdk.AwsNoValue().toString();
cache = {
type: 'S3',
location: cdk.Fn.join('/', [props.cacheBucket.bucketName, cacheDir]),
};
props.cacheBucket.grantReadWrite(this.role);
}
this.buildImage = (props.environment && props.environment.buildImage) || LinuxBuildImage.UBUNTU_14_04_BASE;
// let source "bind" to the project. this usually involves granting permissions
// for the code build role to interact with the source.
this.source = props.source || new NoSource();
this.source._bind(this);
const artifacts = this.parseArtifacts(props);
artifacts._bind(this);
// Inject download commands for asset if requested
const environmentVariables = props.environmentVariables || {};
const buildSpec = props.buildSpec || {};
if (props.buildScriptAsset) {
environmentVariables[S3_BUCKET_ENV] = { value: props.buildScriptAsset.s3BucketName };
environmentVariables[S3_KEY_ENV] = { value: props.buildScriptAsset.s3ObjectKey };
extendBuildSpec(buildSpec, this.buildImage.runScriptBuildspec(props.buildScriptAssetEntrypoint || 'build.sh'));
props.buildScriptAsset.grantRead(this.role);
}
// Render the source and add in the buildspec
const sourceJson = this.source.toSourceJSON();
if (typeof buildSpec === 'string') {
sourceJson.buildSpec = buildSpec; // Filename to buildspec file
} else if (Object.keys(buildSpec).length > 0) {
// We have to pretty-print the buildspec, otherwise
// CodeBuild will not recognize it as an inline buildspec.
sourceJson.buildSpec = JSON.stringify(buildSpec, undefined, 2); // Literal buildspec
} else if (this.source.type === SourceType.None) {
throw new Error("If the Project's source is NoSource, you need to provide a buildSpec");
}
this._secondarySources = [];
for (const secondarySource of props.secondarySources || []) {
this.addSecondarySource(secondarySource);
}
this._secondaryArtifacts = [];
for (const secondaryArtifact of props.secondaryArtifacts || []) {
this.addSecondaryArtifact(secondaryArtifact);
}
this.validateCodePipelineSettings(artifacts);
const resource = new CfnProject(this, 'Resource', {
description: props.description,
source: sourceJson,
artifacts: artifacts.toArtifactsJSON(),
serviceRole: this.role.roleArn,
environment: this.renderEnvironment(props.environment, environmentVariables),
encryptionKey: props.encryptionKey && props.encryptionKey.keyArn,
badgeEnabled: props.badge,
cache,
name: props.projectName,
timeoutInMinutes: props.timeout,
secondarySources: new cdk.Token(() => this.renderSecondarySources()),
secondaryArtifacts: new cdk.Token(() => this.renderSecondaryArtifacts()),
triggers: this.source.buildTriggers(),
});
this.projectArn = resource.projectArn;
this.projectName = resource.ref;
this.addToRolePolicy(this.createLoggingPermission());
}
/**
* Export this Project. Allows referencing this Project in a different CDK Stack.
*/
public export(): ProjectImportProps {
return {
projectName: new cdk.Output(this, 'ProjectName', { value: this.projectName }).makeImportValue().toString(),
};
}
/**
* 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.addToPolicy(statement);
}
}
/**
* Adds a secondary source to the Project.
*
* @param secondarySource the source to add as a secondary source
* @see https://docs.aws.amazon.com/codebuild/latest/userguide/sample-multi-in-out.html
*/
public addSecondarySource(secondarySource: BuildSource): void {
if (!secondarySource.identifier) {
throw new Error('The identifier attribute is mandatory for secondary sources');
}
secondarySource._bind(this);
this._secondarySources.push(secondarySource);
}
/**
* Adds a secondary artifact to the Project.
*
* @param secondaryArtifact the artifact to add as a secondary artifact
* @see https://docs.aws.amazon.com/codebuild/latest/userguide/sample-multi-in-out.html
*/
public addSecondaryArtifact(secondaryArtifact: BuildArtifacts): any {
if (!secondaryArtifact.identifier) {
throw new Error("The identifier attribute is mandatory for secondary artifacts");
}
secondaryArtifact._bind(this);
this._secondaryArtifacts.push(secondaryArtifact);
}
/**
* @override
*/
protected validate(): string[] {
const ret = new Array<string>();
if (this.source.type === SourceType.CodePipeline) {
if (this._secondarySources.length > 0) {
ret.push('A Project with a CodePipeline Source cannot have secondary sources. ' +
"Use the CodeBuild Pipeline Actions' `additionalInputArtifacts` property instead");
}
if (this._secondaryArtifacts.length > 0) {
ret.push('A Project with a CodePipeline Source cannot have secondary artifacts. ' +
"Use the CodeBuild Pipeline Actions' `additionalOutputArtifactNames` property instead");
}
}
return ret;
}
private createLoggingPermission() {
const logGroupArn = this.node.stack.formatArn({
service: 'logs',
resource: 'log-group',
sep: ':',
resourceName: `/aws/codebuild/${this.projectName}`,
});
const logGroupStarArn = `${logGroupArn}:*`;
const p = new iam.PolicyStatement();
p.allow();
p.addResource(logGroupArn);
p.addResource(logGroupStarArn);
p.addAction('logs:CreateLogGroup');
p.addAction('logs:CreateLogStream');
p.addAction('logs:PutLogEvents');
return p;
}
private renderEnvironment(env: BuildEnvironment = {},
projectVars: { [name: string]: BuildEnvironmentVariable } = {}):
CfnProject.EnvironmentProperty {
const vars: { [name: string]: BuildEnvironmentVariable } = {};
const containerVars = env.environmentVariables || {};
// first apply environment variables from the container definition
for (const name of Object.keys(containerVars)) {
vars[name] = containerVars[name];
}
// now apply project-level vars
for (const name of Object.keys(projectVars)) {
vars[name] = projectVars[name];
}
const hasEnvironmentVars = Object.keys(vars).length > 0;
const errors = this.buildImage.validate(env);
if (errors.length > 0) {
throw new Error("Invalid CodeBuild environment: " + errors.join('\n'));
}
return {
type: this.buildImage.type,
image: this.buildImage.imageId,
privilegedMode: env.privileged || false,
computeType: env.computeType || this.buildImage.defaultComputeType,
environmentVariables: !hasEnvironmentVars ? undefined : Object.keys(vars).map(name => ({
name,
type: vars[name].type || BuildEnvironmentVariableType.PlainText,
value: vars[name].value
}))
};
}
private renderSecondarySources(): CfnProject.SourceProperty[] | undefined {
return this._secondarySources.length === 0
? undefined
: this._secondarySources.map((secondarySource) => secondarySource.toSourceJSON());
}
private renderSecondaryArtifacts(): CfnProject.ArtifactsProperty[] | undefined {
return this._secondaryArtifacts.length === 0
? undefined
: this._secondaryArtifacts.map((secondaryArtifact) => secondaryArtifact.toArtifactsJSON());
}
private parseArtifacts(props: ProjectProps) {
if (props.artifacts) {
return props.artifacts;
}
if (this.source.toSourceJSON().type === CODEPIPELINE_TYPE) {
return new CodePipelineBuildArtifacts();
} else {
return new NoBuildArtifacts();
}
}
private validateCodePipelineSettings(artifacts: BuildArtifacts) {
const sourceType = this.source.toSourceJSON().type;
const artifactsType = artifacts.toArtifactsJSON().type;
if ((sourceType === CODEPIPELINE_TYPE || artifactsType === CODEPIPELINE_TYPE) &&
(sourceType !== artifactsType)) {
throw new Error('Both source and artifacts must be set to CodePipeline');
}
}
}
/**
* Build machine compute type.
*/
export enum ComputeType {
Small = 'BUILD_GENERAL1_SMALL',
Medium = 'BUILD_GENERAL1_MEDIUM',
Large = 'BUILD_GENERAL1_LARGE'
}
export interface BuildEnvironment {
/**
* The image used for the builds.
*
* @default LinuxBuildImage.UBUNTU_14_04_BASE
*/
buildImage?: IBuildImage;
/**
* The type of compute to use for this build.
* See the {@link ComputeType} enum for the possible values.
*
* @default taken from {@link #buildImage#defaultComputeType}
*/
computeType?: ComputeType;
/**
* Indicates how the project builds Docker images. Specify true to enable
* running the Docker daemon inside a Docker container. This value must be
* set to true only if this build project will be used to build Docker
* images, and the specified build environment image is not one provided by
* AWS CodeBuild with Docker support. Otherwise, all associated builds that
* attempt to interact with the Docker daemon will fail.
*
* @default false
*/
privileged?: boolean;
/**
* The environment variables that your builds can use.
*/
environmentVariables?: { [name: string]: BuildEnvironmentVariable };
}
/**
* Represents a Docker image used for the CodeBuild Project builds.
* Use the concrete subclasses, either:
* {@link LinuxBuildImage} or {@link WindowsBuildImage}.
*/
export interface IBuildImage {
/**
* The type of build environment.
*/
readonly type: string;
/**
* The Docker image identifier that the build environment uses.
*
* @see https://docs.aws.amazon.com/codebuild/latest/userguide/build-env-ref-available.html
*/
readonly imageId: string;
/**
* The default {@link ComputeType} to use with this image,
* if one was not specified in {@link BuildEnvironment#computeType} explicitly.
*/
readonly defaultComputeType: ComputeType;
/**
* Allows the image a chance to validate whether the passed configuration is correct.
*
* @param buildEnvironment the current build environment
*/
validate(buildEnvironment: BuildEnvironment): string[];
/**
* Make a buildspec to run the indicated script
*/
runScriptBuildspec(entrypoint: string): any;
}
/**
* A CodeBuild image running Linux.
*
* This class has a bunch of public constants that represent the most popular images.
*
* You can also specify a custom image using one of the static methods:
*
* - LinuxBuildImage.fromDockerHub(image)
* - LinuxBuildImage.fromEcrRepository(repo[, tag])
* - LinuxBuildImage.fromAsset(parent, id, props)
*
*
* @see https://docs.aws.amazon.com/codebuild/latest/userguide/build-env-ref-available.html
*/
export class LinuxBuildImage implements IBuildImage {
public static readonly UBUNTU_14_04_BASE = new LinuxBuildImage('aws/codebuild/ubuntu-base:14.04');
public static readonly UBUNTU_14_04_ANDROID_JAVA8_24_4_1 = new LinuxBuildImage('aws/codebuild/android-java-8:24.4.1');
public static readonly UBUNTU_14_04_ANDROID_JAVA8_26_1_1 = new LinuxBuildImage('aws/codebuild/android-java-8:26.1.1');
public static readonly UBUNTU_14_04_DOCKER_17_09_0 = new LinuxBuildImage('aws/codebuild/docker:17.09.0');
public static readonly UBUNTU_14_04_GOLANG_1_10 = new LinuxBuildImage('aws/codebuild/golang:1.10');
public static readonly UBUNTU_14_04_OPEN_JDK_8 = new LinuxBuildImage('aws/codebuild/java:openjdk-8');
public static readonly UBUNTU_14_04_OPEN_JDK_9 = new LinuxBuildImage('aws/codebuild/java:openjdk-9');
public static readonly UBUNTU_14_04_NODEJS_10_1_0 = new LinuxBuildImage('aws/codebuild/nodejs:10.1.0');
public static readonly UBUNTU_14_04_NODEJS_8_11_0 = new LinuxBuildImage('aws/codebuild/nodejs:8.11.0');
public static readonly UBUNTU_14_04_NODEJS_6_3_1 = new LinuxBuildImage('aws/codebuild/nodejs:6.3.1');
public static readonly UBUNTU_14_04_PHP_5_6 = new LinuxBuildImage('aws/codebuild/php:5.6');
public static readonly UBUNTU_14_04_PHP_7_0 = new LinuxBuildImage('aws/codebuild/php:7.0');
public static readonly UBUNTU_14_04_PYTHON_3_6_5 = new LinuxBuildImage('aws/codebuild/python:3.6.5');
public static readonly UBUNTU_14_04_PYTHON_3_5_2 = new LinuxBuildImage('aws/codebuild/python:3.5.2');
public static readonly UBUNTU_14_04_PYTHON_3_4_5 = new LinuxBuildImage('aws/codebuild/python:3.4.5');
public static readonly UBUNTU_14_04_PYTHON_3_3_6 = new LinuxBuildImage('aws/codebuild/python:3.3.6');
public static readonly UBUNTU_14_04_PYTHON_2_7_12 = new LinuxBuildImage('aws/codebuild/python:2.7.12');
public static readonly UBUNTU_14_04_RUBY_2_5_1 = new LinuxBuildImage('aws/codebuild/ruby:2.5.1');
public static readonly UBUNTU_14_04_RUBY_2_3_1 = new LinuxBuildImage('aws/codebuild/ruby:2.3.1');
public static readonly UBUNTU_14_04_RUBY_2_2_5 = new LinuxBuildImage('aws/codebuild/ruby:2.2.5');
public static readonly UBUNTU_14_04_DOTNET_CORE_1_1 = new LinuxBuildImage('aws/codebuild/dot-net:core-1');
public static readonly UBUNTU_14_04_DOTNET_CORE_2_0 = new LinuxBuildImage('aws/codebuild/dot-net:core-2.0');
public static readonly UBUNTU_14_04_DOTNET_CORE_2_1 = new LinuxBuildImage('aws/codebuild/dot-net:core-2.1');
/**
* @returns a Linux build image from a Docker Hub image.
*/
public static fromDockerHub(name: string): LinuxBuildImage {
return new LinuxBuildImage(name);
}
/**
* @returns A Linux build image from an ECR repository.
*
* NOTE: if the repository is external (i.e. imported), then we won't be able to add
* a resource policy statement for it so CodeBuild can pull the image.
*
* @see https://docs.aws.amazon.com/codebuild/latest/userguide/sample-ecr.html
*
* @param repository The ECR repository
* @param tag Image tag (default "latest")
*/
public static fromEcrRepository(repository: ecr.IRepository, tag: string = 'latest'): LinuxBuildImage {
const image = new LinuxBuildImage(repository.repositoryUriForTag(tag));
repository.addToResourcePolicy(ecrAccessForCodeBuildService());
return image;
}
/**
* Uses an Docker image asset as a Linux build image.
*/
public static fromAsset(scope: cdk.Construct, id: string, props: DockerImageAssetProps): LinuxBuildImage {
const asset = new DockerImageAsset(scope, id, props);
const image = new LinuxBuildImage(asset.imageUri);
// allow this codebuild to pull this image (CodeBuild doesn't use a role, so
// we can't use `asset.grantUseImage()`.
asset.repository.addToResourcePolicy(ecrAccessForCodeBuildService());
return image;
}
public readonly type = 'LINUX_CONTAINER';
public readonly defaultComputeType = ComputeType.Small;
private constructor(public readonly imageId: string) {
}
public validate(_: BuildEnvironment): string[] {