forked from awslabs/landing-zone-accelerator-on-aws
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpipeline.ts
1348 lines (1257 loc) · 51.7 KB
/
pipeline.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
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
import * as cdk from 'aws-cdk-lib';
import { NagSuppressions } from 'cdk-nag';
import * as codebuild from 'aws-cdk-lib/aws-codebuild';
import * as codecommit from 'aws-cdk-lib/aws-codecommit';
import * as codepipeline from 'aws-cdk-lib/aws-codepipeline';
import * as codepipeline_actions from 'aws-cdk-lib/aws-codepipeline-actions';
import * as iam from 'aws-cdk-lib/aws-iam';
import { Construct } from 'constructs';
import { Bucket, BucketEncryptionType, ServiceLinkedRole } from '@aws-accelerator/constructs';
import { AcceleratorStage } from './accelerator-stage';
import * as config_repository from './config-repository';
import { AcceleratorToolkitCommand } from './toolkit';
import { Repository } from '@aws-cdk-extensions/cdk-extensions';
import { CONTROL_TOWER_LANDING_ZONE_VERSION } from '@aws-accelerator/utils/lib/control-tower';
import { ControlTowerLandingZoneConfig } from '@aws-accelerator/config';
import { getNodeVersion } from '@aws-accelerator/utils/lib/common-functions';
export interface AcceleratorPipelineProps {
readonly toolkitRole: cdk.aws_iam.Role;
readonly awsCodeStarSupportedRegions: string[];
readonly sourceRepository: string;
readonly sourceRepositoryOwner: string;
readonly sourceRepositoryName: string;
readonly sourceBranchName: string;
readonly sourceBucketName: string;
readonly sourceBucketObject: string;
readonly sourceBucketKmsKeyArn?: string;
readonly enableApprovalStage: boolean;
readonly qualifier?: string;
readonly managementAccountId?: string;
readonly managementAccountRoleName?: string;
readonly managementAccountEmail: string;
readonly logArchiveAccountEmail: string;
readonly auditAccountEmail: string;
readonly controlTowerEnabled: string;
/**
* List of email addresses to be notified when pipeline is waiting for manual approval stage.
* If pipeline do not have approval stage enabled, this value will have no impact.
*/
readonly approvalStageNotifyEmailList?: string;
readonly partition: string;
/**
* Indicates location of the LZA configuration files
*/
readonly configRepositoryLocation: string;
/**
* Optional CodeConnection ARN to specify a 3rd-party configuration repository
*/
readonly codeconnectionArn: string;
/**
* Flag indicating installer using existing CodeCommit repository
*/
readonly useExistingConfigRepo: boolean;
/**
* User defined pre-existing config repository name
*/
readonly configRepositoryName: string;
/**
* User defined pre-existing config repository branch name
*/
readonly configRepositoryBranchName: string;
/**
* Accelerator configuration repository owner (CodeConnection only)
*/
readonly configRepositoryOwner: string;
/**
* Accelerator resource name prefixes
*/
readonly prefixes: {
/**
* Use this prefix value to name resources like -
AWS IAM Role names, AWS Lambda Function names, AWS Cloudwatch log groups names, AWS CloudFormation stack names, AWS CodePipeline names, AWS CodeBuild project names
*
*/
readonly accelerator: string;
/**
* Use this prefix value to name AWS CodeCommit repository
*/
readonly repoName: string;
/**
* Use this prefix value to name AWS S3 bucket
*/
readonly bucketName: string;
/**
* Use this prefix value to name AWS SSM parameter
*/
readonly ssmParamName: string;
/**
* Use this prefix value to name AWS KMS alias
*/
readonly kmsAlias: string;
/**
* Use this prefix value to name AWS SNS topic
*/
readonly snsTopicName: string;
/**
* Use this prefix value to name AWS Secrets
*/
readonly secretName: string;
/**
* Use this prefix value to name AWS CloudTrail CloudWatch log group
*/
readonly trailLogName: string;
/**
* Use this prefix value to name AWS Glue database
*/
readonly databaseName: string;
};
/**
* Boolean for single account mode (i.e. AWS Jam or Workshop)
*/
readonly enableSingleAccountMode: boolean;
/**
* Accelerator pipeline account id, for external deployment it will be pipeline account otherwise management account
*/
pipelineAccountId: string;
/**
* Flag indicating existing role
*/
readonly useExistingRoles: boolean;
/**
* AWS Control Tower Landing Zone identifier
*/
readonly landingZoneIdentifier?: string;
/**
* Accelerator region by region deploy order
*/
readonly regionByRegionDeploymentOrder?: string;
}
enum BuildLogLevel {
ERROR = 'error',
INFO = 'info',
}
/**
* Dictionary of all Action names in one place
* in case we want to change the action name it should be done here
*/
const coreActions: [AcceleratorStage, string][] = [
[AcceleratorStage.BOOTSTRAP, 'Bootstrap'],
[AcceleratorStage.KEY, 'Key'],
[AcceleratorStage.LOGGING, 'Logging'],
[AcceleratorStage.ORGANIZATIONS, 'Organizations'],
[AcceleratorStage.SECURITY_AUDIT, 'Security_Audit'],
[AcceleratorStage.NETWORK_PREP, 'Network_Prepare'],
[AcceleratorStage.SECURITY, 'Security'],
[AcceleratorStage.OPERATIONS, 'Operations'],
[AcceleratorStage.NETWORK_VPC, 'Network_VPCs'],
[AcceleratorStage.SECURITY_RESOURCES, 'Security_Resources'],
[AcceleratorStage.IDENTITY_CENTER, 'Identity_Center'],
[AcceleratorStage.NETWORK_ASSOCIATIONS, 'Network_Associations'],
[AcceleratorStage.CUSTOMIZATIONS, 'Customizations'],
[AcceleratorStage.FINALIZE, 'Finalize'],
];
const otherActions: [AcceleratorStage, string][] = [
[AcceleratorStage.PREPARE, 'Prepare'],
[AcceleratorStage.ACCOUNTS, 'Accounts'],
[AcceleratorStage.IMPORT_ASEA_RESOURCES, 'ImportAseaResources'],
[AcceleratorStage.POST_IMPORT_ASEA_RESOURCES, 'PostImportAseaResources'],
];
const actionNames = Object.fromEntries([...coreActions, ...otherActions]);
/**
* AWS Accelerator Pipeline Class, which creates the pipeline for AWS Landing zone
*/
export class AcceleratorPipeline extends Construct {
private readonly pipelineRole: iam.Role;
private readonly toolkitProject: codebuild.PipelineProject;
private readonly buildOutput: codepipeline.Artifact;
private readonly acceleratorRepoArtifact: codepipeline.Artifact;
private readonly configRepoArtifact: codepipeline.Artifact;
private readonly pipelineArtifacts: codepipeline.Artifact[];
private readonly pipeline: codepipeline.Pipeline;
private readonly props: AcceleratorPipelineProps;
private readonly installerKey: cdk.aws_kms.Key;
private readonly configBucketName: string;
private readonly serverAccessLogsBucketNameSsmParam: string;
private readonly controlTowerLandingZoneConfig?: ControlTowerLandingZoneConfig;
private readonly diffS3Uri: string;
constructor(scope: Construct, id: string, props: AcceleratorPipelineProps) {
super(scope, id);
this.props = props;
//
// Get default AWS Control Tower Landing Zone configuration
//
this.controlTowerLandingZoneConfig = this.getControlTowerLandingZoneConfiguration();
//
// Fields can be changed based on qualifier property
let acceleratorKeyArnSsmParameterName = `${props.prefixes.ssmParamName}/installer/kms/key-arn`;
let secureBucketName = `${props.prefixes.bucketName}-pipeline-${cdk.Stack.of(this).account}-${
cdk.Stack.of(this).region
}`;
this.configBucketName = `${props.prefixes.bucketName}-config-${cdk.Stack.of(this).account}-${
cdk.Stack.of(this).region
}`;
this.serverAccessLogsBucketNameSsmParam = `${props.prefixes.ssmParamName}/installer-access-logs-bucket-name`;
let pipelineName = `${props.prefixes.accelerator}-Pipeline`;
let buildProjectName = `${props.prefixes.accelerator}-BuildProject`;
let toolkitProjectName = `${props.prefixes.accelerator}-ToolkitProject`;
this.diffS3Uri = `s3://${this.props.prefixes.bucketName}-pipeline-${cdk.Stack.of(this).account}-${
cdk.Stack.of(this).region
}/AWSAccelerator-Pipel/Diffs`;
//
// Change the fields when qualifier is present
if (this.props.qualifier) {
acceleratorKeyArnSsmParameterName = `${props.prefixes.ssmParamName}/${this.props.qualifier}/installer/kms/key-arn`;
secureBucketName = `${this.props.qualifier}-pipeline-${cdk.Stack.of(this).account}-${cdk.Stack.of(this).region}`;
this.configBucketName = `${this.props.qualifier}-config-${cdk.Stack.of(this).account}-${
cdk.Stack.of(this).region
}`;
this.serverAccessLogsBucketNameSsmParam = `${props.prefixes.ssmParamName}/${this.props.qualifier}/installer-access-logs-bucket-name`;
pipelineName = `${this.props.qualifier}-pipeline`;
buildProjectName = `${this.props.qualifier}-build-project`;
toolkitProjectName = `${this.props.qualifier}-toolkit-project`;
this.diffS3Uri = `s3://${this.props.qualifier}-pipeline-${cdk.Stack.of(this).account}-${
cdk.Stack.of(this).region
}/AWSAccelerator-Pipel/Diffs`;
}
let nodeEnvVariables: { [p: string]: codebuild.BuildEnvironmentVariable } | undefined;
/**
* This environment variable is only present when user decides to have a custom runtime
* If this environment variable is not present then runtime is set to whatever the value
* is in source/package.json `config.node.version.default`
*/
if (process.env['ACCELERATOR_NODE_VERSION']) {
nodeEnvVariables = {
ACCELERATOR_NODE_VERSION: {
type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
value: getNodeVersion(),
},
};
}
let pipelineAccountEnvVariables: { [p: string]: codebuild.BuildEnvironmentVariable } | undefined;
if (this.props.managementAccountId && this.props.managementAccountRoleName) {
pipelineAccountEnvVariables = {
MANAGEMENT_ACCOUNT_ID: {
type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
value: this.props.managementAccountId,
},
MANAGEMENT_ACCOUNT_ROLE_NAME: {
type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
value: this.props.managementAccountRoleName,
},
};
}
let enableSingleAccountModeEnvVariables: { [p: string]: codebuild.BuildEnvironmentVariable } | undefined;
if (props.enableSingleAccountMode) {
enableSingleAccountModeEnvVariables = {
ACCELERATOR_ENABLE_SINGLE_ACCOUNT_MODE: {
type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
value: true,
},
};
}
const enableAseaMigration = process.env['ENABLE_ASEA_MIGRATION']?.toLowerCase?.() === 'true';
let aseaMigrationModeEnvVariables: { [p: string]: codebuild.BuildEnvironmentVariable } | undefined;
if (enableAseaMigration) {
aseaMigrationModeEnvVariables = {
ENABLE_ASEA_MIGRATION: {
type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
value: 'true',
},
ASEA_MAPPING_BUCKET: {
type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
value: `${props.prefixes.accelerator}-lza-resource-mapping-${cdk.Stack.of(this).account}`.toLowerCase(),
},
ASEA_MAPPING_FILE: {
type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
value: 'aseaResources.json',
},
};
}
// Get installer key
this.installerKey = cdk.aws_kms.Key.fromKeyArn(
this,
'AcceleratorKey',
cdk.aws_ssm.StringParameter.valueForStringParameter(this, acceleratorKeyArnSsmParameterName),
) as cdk.aws_kms.Key;
const bucket = new Bucket(this, 'SecureBucket', {
encryptionType: BucketEncryptionType.SSE_KMS,
s3BucketName: secureBucketName,
kmsKey: this.installerKey,
serverAccessLogsBucketName: cdk.aws_ssm.StringParameter.valueForStringParameter(
this,
this.serverAccessLogsBucketNameSsmParam,
),
});
/**
* Pipeline
*/
this.pipelineRole = new iam.Role(this, 'PipelineRole', {
assumedBy: new iam.ServicePrincipal('codepipeline.amazonaws.com'),
});
/**
* Optional context flag "s3-source-kms-key-arn" for encrypted S3 buckets containing LZA source code
* requires pipeline roles to have additional KMS key access permissions
*/
if (this.props.sourceBucketKmsKeyArn) {
this.pipelineRole.addToPolicy(
new cdk.aws_iam.PolicyStatement({
actions: ['kms:Decrypt', 'kms:GenerateDataKey'],
resources: [this.props.sourceBucketKmsKeyArn],
}),
);
}
this.pipeline = new codepipeline.Pipeline(this, 'Resource', {
pipelineName: pipelineName,
artifactBucket: bucket.getS3Bucket(),
role: this.pipelineRole,
});
this.acceleratorRepoArtifact = new codepipeline.Artifact('Source');
this.configRepoArtifact = new codepipeline.Artifact('Config');
/**
* Formatting Artifact name from network-vpc to Network_Vpc
* strapes are not allowed
*/
const formatArtifactName = (stage: AcceleratorStage): string => {
return stage
.split('-')
.map(name => name.charAt(0).toUpperCase() + name.slice(1))
.join('_');
};
this.pipelineArtifacts = coreActions.map(([stage]) => new codepipeline.Artifact(formatArtifactName(stage)));
let sourceAction:
| cdk.aws_codepipeline_actions.CodeCommitSourceAction
| cdk.aws_codepipeline_actions.S3SourceAction
| cdk.aws_codepipeline_actions.GitHubSourceAction;
if (this.props.sourceRepository === 'codecommit') {
sourceAction = new codepipeline_actions.CodeCommitSourceAction({
actionName: 'Source',
repository: codecommit.Repository.fromRepositoryName(this, 'SourceRepo', this.props.sourceRepositoryName),
branch: this.props.sourceBranchName,
output: this.acceleratorRepoArtifact,
trigger: codepipeline_actions.CodeCommitTrigger.NONE,
role: this.pipelineRole,
});
} else if (this.props.sourceBucketName && this.props.sourceBucketName.length > 0) {
// hidden parameter to use S3 for source code via cdk context
const bucket = cdk.aws_s3.Bucket.fromBucketAttributes(this, 'ExistingBucket', {
bucketName: this.props.sourceBucketName,
...(this.props.sourceBucketKmsKeyArn && {
encryptionKey: cdk.aws_kms.Key.fromKeyArn(this, 'S3SourceKmsKey', this.props.sourceBucketKmsKeyArn),
}),
});
sourceAction = new codepipeline_actions.S3SourceAction({
actionName: 'Source',
bucket: bucket,
bucketKey: this.props.sourceBucketObject,
output: this.acceleratorRepoArtifact,
trigger: codepipeline_actions.S3Trigger.NONE,
role: this.pipelineRole,
});
} else {
sourceAction = new cdk.aws_codepipeline_actions.GitHubSourceAction({
actionName: 'Source',
owner: this.props.sourceRepositoryOwner,
repo: this.props.sourceRepositoryName,
branch: this.props.sourceBranchName,
oauthToken: cdk.SecretValue.secretsManager('accelerator/github-token'),
output: this.acceleratorRepoArtifact,
trigger: cdk.aws_codepipeline_actions.GitHubTrigger.NONE,
});
}
if (this.props.configRepositoryLocation === 's3') {
const s3ConfigRepository = this.getS3ConfigRepository();
this.pipeline.addStage({
stageName: 'Source',
actions: [
sourceAction,
new codepipeline_actions.S3SourceAction({
actionName: 'Configuration',
bucket: s3ConfigRepository,
bucketKey: 'zipped/aws-accelerator-config.zip',
output: this.configRepoArtifact,
trigger: codepipeline_actions.S3Trigger.NONE,
variablesNamespace: 'Config-Vars',
}),
],
});
} else if (this.props.configRepositoryLocation === 'codeconnection' && this.props.codeconnectionArn !== '') {
this.pipeline.addStage({
stageName: 'Source',
actions: [
sourceAction,
new codepipeline_actions.CodeStarConnectionsSourceAction({
actionName: 'Configuration',
branch: this.props.configRepositoryBranchName,
connectionArn: this.props.codeconnectionArn,
owner: this.props.configRepositoryOwner,
repo: this.props.configRepositoryName,
output: this.configRepoArtifact,
variablesNamespace: 'Config-Vars',
}),
],
});
} else {
const configRepositoryBranchName = this.props.useExistingConfigRepo
? this.props.configRepositoryBranchName ?? 'main'
: 'main';
const codecommitConfigRepository = this.getCodeCommitConfigRepository(configRepositoryBranchName);
this.pipeline.addStage({
stageName: 'Source',
actions: [
sourceAction,
new codepipeline_actions.CodeCommitSourceAction({
actionName: 'Configuration',
repository: codecommitConfigRepository,
branch: configRepositoryBranchName,
output: this.configRepoArtifact,
trigger: codepipeline_actions.CodeCommitTrigger.NONE,
variablesNamespace: 'Config-Vars',
role: this.pipelineRole,
}),
],
});
}
/**
* Build Stage
*/
const buildRole = new iam.Role(this, 'BuildRole', {
assumedBy: new iam.ServicePrincipal('codebuild.amazonaws.com'),
});
const validateConfigPolicyDocument = new cdk.aws_iam.PolicyDocument({
statements: [
new cdk.aws_iam.PolicyStatement({
effect: cdk.aws_iam.Effect.ALLOW,
actions: ['organizations:ListAccounts', 'ssm:GetParameter'],
resources: ['*'],
}),
],
});
const validateConfigPolicy = new cdk.aws_iam.ManagedPolicy(this, 'ValidateConfigPolicyDocument', {
document: validateConfigPolicyDocument,
});
buildRole.addManagedPolicy(validateConfigPolicy);
if (this.props.managementAccountId && this.props.managementAccountRoleName) {
const assumeExternalDeploymentRolePolicyDocument = new cdk.aws_iam.PolicyDocument({
statements: [
new cdk.aws_iam.PolicyStatement({
effect: cdk.aws_iam.Effect.ALLOW,
actions: ['sts:AssumeRole'],
resources: [
`arn:${this.props.partition}:iam::${this.props.managementAccountId}:role/${this.props.managementAccountRoleName}`,
],
}),
],
});
/**
* Create an IAM Policy for the build role to be able to lookup replacement parameters in the external deployment
* target account
*/
const assumeExternalDeploymentRolePolicy = new cdk.aws_iam.ManagedPolicy(this, 'AssumeExternalDeploymentPolicy', {
document: assumeExternalDeploymentRolePolicyDocument,
});
buildRole.addManagedPolicy(assumeExternalDeploymentRolePolicy);
}
// Pipeline/BuildRole/Resource AwsSolutions-IAM4: The IAM user, role, or group uses AWS managed policies.
NagSuppressions.addResourceSuppressionsByPath(
cdk.Stack.of(this),
`${cdk.Stack.of(this).stackName}/Pipeline/BuildRole/Resource`,
[
{
id: 'AwsSolutions-IAM4',
reason: 'AWS Managed policy for External Pipeline Deployment Lookups attached.',
},
],
);
const buildProject = new codebuild.PipelineProject(this, 'BuildProject', {
projectName: buildProjectName,
encryptionKey: this.installerKey,
role: buildRole,
buildSpec: codebuild.BuildSpec.fromObject({
version: '0.2',
phases: {
install: {
'runtime-versions': {
nodejs: getNodeVersion(),
},
},
pre_build: {
commands: [
`export PACKAGE_VERSION=$(cat source/package.json | grep version | head -1 | awk -F: '{ print $2 }' | sed 's/[",]//g' | tr -d '[:space:]')`,
`if [ "$ACCELERATOR_CHECK_VERSION" = "yes" ]; then
if [ "$PACKAGE_VERSION" != "$ACCELERATOR_PIPELINE_VERSION" ]; then
echo "ERROR: Accelerator package version in Source does not match currently installed LZA version. Please ensure that the Installer stack has been updated prior to updating the Source code in CodePipeline."
exit 1
fi
fi`,
],
},
build: {
commands: [
'env',
'cd source',
`if [ "${cdk.Stack.of(this).partition}" = "aws-cn" ]; then
sed -i "s#registry.yarnpkg.com#registry.npmmirror.com#g" yarn.lock;
yarn config set registry https://registry.npmmirror.com
fi`,
'if [ -f .yarnrc ]; then yarn install --use-yarnrc .yarnrc; else yarn install; fi',
'yarn build',
'yarn validate-config $CODEBUILD_SRC_DIR_Config',
],
},
},
artifacts: {
files: ['**/*'],
'enable-symlinks': 'yes',
},
}),
environment: {
buildImage: codebuild.LinuxBuildImage.STANDARD_7_0,
privileged: false,
computeType: codebuild.ComputeType.LARGE,
environmentVariables: {
NODE_OPTIONS: {
type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
value: '--max_old_space_size=12288 --no-warnings',
},
PARTITION: {
type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
value: cdk.Stack.of(this).partition,
},
ACCELERATOR_PIPELINE_VERSION: {
type: codebuild.BuildEnvironmentVariableType.PARAMETER_STORE,
value: `${props.prefixes.ssmParamName}/${cdk.Stack.of(this).stackName}/version`,
},
ACCELERATOR_CHECK_VERSION: {
type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
value: 'yes',
},
...enableSingleAccountModeEnvVariables,
...pipelineAccountEnvVariables,
...nodeEnvVariables,
},
},
cache: codebuild.Cache.local(codebuild.LocalCacheMode.SOURCE),
});
/**
* Toolkit CodeBuild project is used to run all Accelerator stages, including diff
* First it executes synth of all Pipeline stages and then diff within the same container.
* CloudFormation templates are then reused for all further stages
* Diff files are uploaded to pipeline S3 bucket - consideration needed if running in external account
*/
this.toolkitProject = new codebuild.PipelineProject(this, 'ToolkitProject', {
projectName: toolkitProjectName,
encryptionKey: this.installerKey,
role: this.props.toolkitRole,
timeout: cdk.Duration.hours(8),
buildSpec: codebuild.BuildSpec.fromObjectToYaml({
version: 0.2,
phases: {
install: {
'runtime-versions': {
nodejs: getNodeVersion(),
},
},
pre_build: {
commands: [
`export WORK_DIR=source/packages/@aws-accelerator/accelerator
export ARCHIVE_NAME="\${ACCELERATOR_STAGE}.tgz"
export DIFFS_DIR="${this.diffS3Uri}"
export STAGE_ARTIFACT=$(echo "$ACCELERATOR_STAGE" | sed 's/-/ /g' | awk '{for (i=1; i<=NF; ++i) $i=toupper(substr($i,1,1))tolower(substr($i,2))}1' | sed 's/ /_/g')
`,
],
},
build: {
commands: [
'env',
'cd $WORK_DIR',
`if [ "prepare" = "\${ACCELERATOR_STAGE}" ]; then set -e && LOG_LEVEL=${
BuildLogLevel.INFO
} yarn run ts-node ../lza-modules/bin/runner.ts --module control-tower --partition ${
cdk.Aws.PARTITION
} --use-existing-role ${
this.props.useExistingRoles ? 'Yes' : 'No'
} --config-dir $CODEBUILD_SRC_DIR_Config; fi`,
`if [ "prepare" = "\${ACCELERATOR_STAGE}" ] && [ -z "\${ACCELERATOR_NO_ORG_MODULE}" ]; then set -e && LOG_LEVEL=info && yarn run ts-node ../lza-modules/bin/runner.ts --module aws-organizations --partition ${
cdk.Aws.PARTITION
} --use-existing-role ${
this.props.useExistingRoles ? 'Yes' : 'No'
} --config-dir $CODEBUILD_SRC_DIR_Config; else echo "Module aws-organizations execution skipped by environment settings."; fi`,
`if [ "prepare" = "\${ACCELERATOR_STAGE}" ]; then set -e && LOG_LEVEL=info && yarn run ts-node ../lza-modules/bin/runner.ts --module account-alias --partition ${
cdk.Aws.PARTITION
} --use-existing-role ${
this.props.useExistingRoles ? 'Yes' : 'No'
} --config-dir $CODEBUILD_SRC_DIR_Config; fi`,
`if [ "prepare" = "\${ACCELERATOR_STAGE}" ]; then set -e && yarn run ts-node ./lib/prerequisites.ts --config-dir $CODEBUILD_SRC_DIR_Config --partition ${cdk.Aws.PARTITION} --minimal; fi`,
'export FULL_SYNTH="true"',
'if [ $ASEA_MAPPING_BUCKET ]; then aws s3api head-object --bucket $ASEA_MAPPING_BUCKET --key $ASEA_MAPPING_FILE >/dev/null 2>&1 || export FULL_SYNTH="false"; fi;',
`if [ "\${CDK_OPTIONS}" = "bootstrap" ]; then
if [ $FULL_SYNTH = "true" ]; then
set -e && yarn run ts-node --transpile-only cdk.ts synth --stage $ACCELERATOR_STAGE --require-approval never --config-dir $CODEBUILD_SRC_DIR_Config --partition ${cdk.Aws.PARTITION};
fi
if [ "\${ACCELERATOR_STAGE}" = "bootstrap" ]; then
yarn run ts-node --transpile-only cdk.ts synth --stage $ACCELERATOR_STAGE --require-approval never --config-dir $CODEBUILD_SRC_DIR_Config --partition ${cdk.Aws.PARTITION};
yarn run ts-node --transpile-only cdk.ts $CDK_OPTIONS --require-approval never --config-dir $CODEBUILD_SRC_DIR_Config --partition ${cdk.Aws.PARTITION} --app cdk.out;
fi
if [ $FULL_SYNTH = "true" ]; then
set -e && tar -czf cf_$ARCHIVE_NAME -C cdk.out .;
else
touch full-synth-false.txt;
fi
if [ "\${ACCELERATOR_ENABLE_APPROVAL_STAGE}" = "Yes" ] && [ "$ACCELERATOR_STAGE" != "bootstrap" ]; then
set -e && yarn run ts-node --transpile-only cdk.ts diff --stage $ACCELERATOR_STAGE --require-approval never --config-dir $CODEBUILD_SRC_DIR_Config --partition ${cdk.Aws.PARTITION} --app cdk.out;
tar -czf diff_cdk_out_$ARCHIVE_NAME -C cdk.out .
find cdk.out -type f -name "*.diff" -print0 | tar --transform='s|.*/||' -czf diff_$ARCHIVE_NAME --null -T -
aws s3 cp diff_$ARCHIVE_NAME $DIFFS_DIR/$CODEPIPELINE_EXECUTION_ID/
fi
else
eval ARTIFACTS='$'CODEBUILD_SRC_DIR_$STAGE_ARTIFACT
if [ -f "\${ARTIFACTS}/cf_\${ARCHIVE_NAME}" ]; then
mkdir -p cdk.out
tar -xzf $ARTIFACTS/cf_$ARCHIVE_NAME -C cdk.out;
else
set -e && yarn run ts-node --transpile-only cdk.ts synth --stage $ACCELERATOR_STAGE --require-approval never --config-dir $CODEBUILD_SRC_DIR_Config --partition ${cdk.Aws.PARTITION};
fi
set -e && yarn run ts-node --transpile-only cdk.ts $CDK_OPTIONS --require-approval never --config-dir $CODEBUILD_SRC_DIR_Config --partition ${cdk.Aws.PARTITION} --app cdk.out;
fi`,
`if [ "prepare" = "\${ACCELERATOR_STAGE}" ]; then set -e && yarn run ts-node ./lib/prerequisites.ts --config-dir $CODEBUILD_SRC_DIR_Config --partition ${cdk.Aws.PARTITION}; fi`,
],
},
},
artifacts: {
'base-directory': '$WORK_DIR',
files: ['cf_$ARCHIVE_NAME', 'diff_cdk_out_$ARCHIVE_NAME', 'full-synth-false.txt'],
},
}),
environment: {
buildImage: codebuild.LinuxBuildImage.STANDARD_7_0,
privileged: false, // Allow access to the Docker daemon
computeType: codebuild.ComputeType.LARGE,
environmentVariables: {
LOG_LEVEL: {
type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
value: BuildLogLevel.ERROR,
},
NODE_OPTIONS: {
type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
value: '--max_old_space_size=12288 --no-warnings',
},
CDK_METHOD: {
type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
value: 'direct',
},
CDK_NEW_BOOTSTRAP: {
type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
value: '1',
},
ACCELERATOR_QUALIFIER: {
type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
value: this.props.qualifier ? this.props.qualifier : 'aws-accelerator',
},
ACCELERATOR_PREFIX: {
type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
value: props.prefixes.accelerator,
},
ACCELERATOR_REPO_NAME_PREFIX: {
type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
value: props.prefixes.repoName,
},
ACCELERATOR_BUCKET_NAME_PREFIX: {
type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
value: props.prefixes.bucketName,
},
ACCELERATOR_KMS_ALIAS_PREFIX: {
type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
value: props.prefixes.kmsAlias,
},
ACCELERATOR_SSM_PARAM_NAME_PREFIX: {
type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
value: props.prefixes.ssmParamName,
},
ACCELERATOR_SNS_TOPIC_NAME_PREFIX: {
type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
value: props.prefixes.snsTopicName,
},
ACCELERATOR_SECRET_NAME_PREFIX: {
type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
value: props.prefixes.secretName,
},
ACCELERATOR_TRAIL_LOG_NAME_PREFIX: {
type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
value: props.prefixes.trailLogName,
},
ACCELERATOR_DATABASE_NAME_PREFIX: {
type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
value: props.prefixes.databaseName,
},
PIPELINE_ACCOUNT_ID: {
type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
value: props.pipelineAccountId,
},
ENABLE_DIAGNOSTICS_PACK: {
type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
value: process.env['ENABLE_DIAGNOSTICS_PACK'] ?? 'Yes',
},
INSTALLER_STACK_NAME: {
type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
value: process.env['INSTALLER_STACK_NAME'] ?? '',
},
ACCELERATOR_PERMISSION_BOUNDARY: {
type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
value: process.env['ACCELERATOR_PERMISSION_BOUNDARY'] ?? '',
},
CONFIG_REPOSITORY_LOCATION: {
type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
value: process.env['CONFIG_REPOSITORY_LOCATION'] ?? 'codecommit',
},
ACCELERATOR_SKIP_PREREQUISITES: {
type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
value: 'true',
},
ACCELERATOR_ENABLE_APPROVAL_STAGE: {
type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
value: props.enableApprovalStage ? 'Yes' : 'No',
},
USE_EXISTING_CONFIG_REPO: {
type: cdk.aws_codebuild.BuildEnvironmentVariableType.PLAINTEXT,
value: this.props.useExistingConfigRepo,
},
EXISTING_CONFIG_REPOSITORY_NAME: {
type: cdk.aws_codebuild.BuildEnvironmentVariableType.PLAINTEXT,
value: this.props.configRepositoryName,
},
EXISTING_CONFIG_REPOSITORY_BRANCH_NAME: {
type: cdk.aws_codebuild.BuildEnvironmentVariableType.PLAINTEXT,
value: this.props.configRepositoryBranchName,
},
...enableSingleAccountModeEnvVariables,
...pipelineAccountEnvVariables,
...aseaMigrationModeEnvVariables,
...nodeEnvVariables,
},
},
cache: codebuild.Cache.local(codebuild.LocalCacheMode.SOURCE),
});
this.buildOutput = new codepipeline.Artifact('Build');
this.pipeline.addStage({
stageName: 'Build',
actions: [
new codepipeline_actions.CodeBuildAction({
actionName: 'Build',
project: buildProject,
input: this.acceleratorRepoArtifact,
extraInputs: [this.configRepoArtifact],
outputs: [this.buildOutput],
role: this.pipelineRole,
environmentVariables: {
REGION_BY_REGION_DEPLOYMENT_ORDER: {
type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
value: this.props.regionByRegionDeploymentOrder ?? '',
},
},
}),
],
});
/**
* The Prepare stage is used to verify that all prerequisites have been made and that the
* Accelerator can be deployed into the environment
* Creates the accounts
* Creates the ou's if control tower is not enabled
*/
this.pipeline.addStage({
stageName: 'Prepare',
actions: [
this.createToolkitStage({
actionName: actionNames[AcceleratorStage.PREPARE],
command: 'deploy',
stage: AcceleratorStage.PREPARE,
}),
],
});
this.pipeline.addStage({
stageName: 'Accounts',
actions: [
this.createToolkitStage({
actionName: actionNames[AcceleratorStage.ACCOUNTS],
command: 'deploy',
stage: AcceleratorStage.ACCOUNTS,
}),
],
});
this.pipeline.addStage({
stageName: 'Bootstrap',
actions: [
...coreActions.map(([stage, actionName]) =>
this.createToolkitStage({
actionName: actionName,
command: 'bootstrap',
stage: stage,
runOrder: 1,
}),
),
],
});
//
// Add review stage based on parameter
const notificationTopic = this.addReviewStage();
/**
* The Logging stack establishes all the logging assets that are needed in
* all the accounts and will configure:
*
* - An S3 Access Logs bucket for every region in every account
* - The Central Logs bucket in the log-archive account
*
*/
this.pipeline.addStage({
stageName: 'Logging',
actions: [
this.createToolkitStage({
actionName: actionNames[AcceleratorStage.KEY],
command: 'deploy',
stage: AcceleratorStage.KEY,
runOrder: 1,
}),
this.createToolkitStage({
actionName: actionNames[AcceleratorStage.LOGGING],
command: 'deploy',
stage: AcceleratorStage.LOGGING,
runOrder: 2,
}),
],
});
// Adds ASEA Import Resources stage
if (enableAseaMigration) {
this.pipeline.addStage({
stageName: 'ImportAseaResources',
actions: [
this.createToolkitStage({
actionName: actionNames[AcceleratorStage.IMPORT_ASEA_RESOURCES],
command: `deploy`,
stage: AcceleratorStage.IMPORT_ASEA_RESOURCES,
}),
],
});
}
this.pipeline.addStage({
stageName: 'Organization',
actions: [
this.createToolkitStage({
actionName: actionNames[AcceleratorStage.ORGANIZATIONS],
command: 'deploy',
stage: AcceleratorStage.ORGANIZATIONS,
}),
],
});
this.pipeline.addStage({
stageName: 'SecurityAudit',
actions: [
this.createToolkitStage({
actionName: actionNames[AcceleratorStage.SECURITY_AUDIT],
command: 'deploy',
stage: AcceleratorStage.SECURITY_AUDIT,
}),
],
});
if (this.props.regionByRegionDeploymentOrder) {
const regions = this.props.regionByRegionDeploymentOrder.split(',').map(r => r.trim());
for (const region of regions) {
this.addDeployStage(region, notificationTopic);
}
this.pipeline.addStage({
stageName: 'Finalize',
actions: [
this.createToolkitStage({
actionName: 'Finalize',
command: 'deploy',
stage: AcceleratorStage.FINALIZE,
}),
],
});
} else {
this.addDeployStage();
}
// Add ASEA Import Resources
if (enableAseaMigration) {
this.pipeline.addStage({
stageName: 'PostImportAseaResources',
actions: [
this.createToolkitStage({
actionName: actionNames[AcceleratorStage.POST_IMPORT_ASEA_RESOURCES],
command: `deploy`,
stage: AcceleratorStage.POST_IMPORT_ASEA_RESOURCES,
}),
],
});
}
// Enable pipeline notification for commercial partition
this.enablePipelineNotification();
}
private getBuildProps(stageName: string, command: string) {
const commonProps = {
input: this.buildOutput,
extraInputs: [this.configRepoArtifact],
};
const excludedArtifacts = ['Source', 'Build', 'Prepare', 'Accounts', 'Bootstrap'];
const matchingArtifact = this.pipelineArtifacts.filter(
artifact => artifact.artifactName?.toLowerCase().replace('_', '-') === stageName.toLowerCase(),
);
return {
...commonProps,
project: this.toolkitProject,
extraInputs: [
...commonProps.extraInputs,
...(command === 'deploy' && stageName && !excludedArtifacts.includes(stageName) ? matchingArtifact : []),
],
outputs: command === 'bootstrap' ? matchingArtifact : [],
};
}
/**
* Add review stage based on parameter
*/
private addReviewStage(): cdk.aws_sns.Topic | undefined {
if (this.props.enableApprovalStage) {
const notificationTopic = new cdk.aws_sns.Topic(this, 'ManualApprovalActionTopic', {
topicName:
(this.props.qualifier ? this.props.qualifier : this.props.prefixes.snsTopicName) + '-pipeline-review-topic',
displayName:
(this.props.qualifier ? this.props.qualifier : this.props.prefixes.snsTopicName) + '-pipeline-review-topic',
masterKey: this.installerKey,
});
let notifyEmails: string[] | undefined = undefined;
if (notificationTopic) {
if (this.props.approvalStageNotifyEmailList) {
notifyEmails = this.props.approvalStageNotifyEmailList.split(',');
}
}
/**