-
Notifications
You must be signed in to change notification settings - Fork 173
Expand file tree
/
Copy pathcodebuild-deployment-template.yaml
More file actions
1944 lines (1817 loc) · 73.7 KB
/
Copy pathcodebuild-deployment-template.yaml
File metadata and controls
1944 lines (1817 loc) · 73.7 KB
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.
# SPDX-License-Identifier: Apache-2.0
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
# Workshop deployment template for CDK projects - CloudFormation
# Version: 1.0.0 - Simplified
AWSTemplateFormatVersion: '2010-09-09'
Description: |
Automates CDK project deployment for workshop environments. Provisions S3 storage, CodeBuild project, and monitoring resources to bootstrap AWS accounts and deploy CDK applications consistently. Includes error handling and cleanup mechanisms for failed deployments.
The pWaitForDeployment parameter controls whether CloudFormation waits for the CDK pipeline to complete before marking the stack as CREATE_COMPLETE. Set to 'false' when manually fixing pipeline issues to allow the stack to complete without waiting for pipeline execution.
For more details, see: https://github.com/aws-samples/one-observability-demo
Metadata:
AWS::CloudFormation::Interface:
ParameterGroups:
- Label:
default: Repository Configuration
Parameters:
- pConfigFileUrl
- pOrganizationName
- pRepositoryName
- pBranchName
- pCodeConnectionArn
- pWorkingFolder
- pApplicationName
- pDisableCleanup
- pCDKStackName
- pParameterStoreBasePath
- pWaitForDeployment
- Label:
default: Network Configuration
Parameters:
- pVpcCidr
- Label:
default: User Defined Tags
Parameters:
- pUserDefinedTagKey1
- pUserDefinedTagValue1
- pUserDefinedTagKey2
- pUserDefinedTagValue2
- pUserDefinedTagKey3
- pUserDefinedTagValue3
- pUserDefinedTagKey4
- pUserDefinedTagValue4
- pUserDefinedTagKey5
- pUserDefinedTagValue5
Parameters:
pDisableCleanup:
Type: String
Description: Disable cleanup in post_build stage if deployment fails
Default: 'false'
AllowedValues:
- 'true'
- 'false'
ConstraintDescription: Must be either 'true' or 'false'
pConfigFileUrl:
Type: String
Description: URL to the initial configuration file
AllowedPattern: ^https?://.*$
ConstraintDescription: Must be a valid HTTP or HTTPS URL
Default: https://raw.githubusercontent.com/aws-samples/one-observability-demo/refs/heads/main/src/presets/default.env
pOrganizationName:
Type: String
Description: GitHub/CodeCommit organization name
AllowedPattern: '[A-Za-z0-9_.-]+'
ConstraintDescription: Must contain only alphanumeric characters, underscores, periods, or hyphens
Default: aws-samples
pRepositoryName:
Type: String
Description: Repository containing the CDK code
AllowedPattern: '[A-Za-z0-9_.-]+'
ConstraintDescription: Must contain only alphanumeric characters, underscores, periods, or hyphens
Default: one-observability-demo
pBranchName:
Type: String
Description: Branch to deploy from
Default: main
AllowedPattern: '[A-Za-z0-9_./-]+'
ConstraintDescription: Must contain only alphanumeric characters, underscores,
periods, slashes, or hyphens
pWorkingFolder:
Type: String
Description: Working folder for deployment
Default: src/cdk
AllowedPattern: '[A-Za-z0-9_.-/]+'
ConstraintDescription: Must contain only alphanumeric characters, underscores, periods, or hyphens
pApplicationName:
Type: String
Description: Application name used for tagging deployed stacks
Default: One Observability Workshop
AllowedPattern: ^[A-Za-z0-9\s_.-]+$
ConstraintDescription: Must contain only alphanumeric characters, spaces, underscores, periods, or hyphens
pUserDefinedTagKey1:
Type: String
Description: Key for user defined tag 1
AllowedPattern: ^(?!aws:)[A-Za-z0-9\s_.:=+-@/]{0,128}
ConstraintDescription: 'Must match the allowable values for a Tag Key. This can
only contain alphanumeric characters or special characters ( _ . : / = + -
or @) up to 128 characters'
Default: WorkshopName
pUserDefinedTagValue1:
Type: String
Description: Value for user defined tag 1
AllowedPattern: ^[\w\s_.:=+-@/]{0,256}$
ConstraintDescription: 'Must match the allowable values for a Tag Value. This
can only contain alphanumeric characters or special characters ( _ . : / =
+ - or @) up to 256 characters'
Default: one-observability-demo
pUserDefinedTagKey2:
Type: String
Description: Key for user defined tag 2
AllowedPattern: ^(?!aws:)[A-Za-z0-9\s_.:=+-@/]{0,128}
ConstraintDescription: 'Must match the allowable values for a Tag Key. This can
only contain alphanumeric characters or special characters ( _ . : / = + -
or @) up to 128 characters'
Default: Version
pUserDefinedTagValue2:
Type: String
Description: Value for user defined tag 2
AllowedPattern: ^[\w\s_.:=+-@/]{0,256}$
ConstraintDescription: 'Must match the allowable values for a Tag Value. This
can only contain alphanumeric characters or special characters ( _ . : / =
+ - or @) up to 256 characters'
Default: 1.0.0
pUserDefinedTagKey3:
Type: String
Description: Key for user defined tag 3
AllowedPattern: ^(?!aws:)[A-Za-z0-9\s_.:=+-@/]{0,128}
ConstraintDescription: 'Must match the allowable values for a Tag Key. This can
only contain alphanumeric characters or special characters ( _ . : / = + -
or @) up to 128 characters'
pUserDefinedTagValue3:
Type: String
Description: Value for user defined tag 3
AllowedPattern: ^[\w\s_.:=+-@/]{0,256}$
ConstraintDescription: 'Must match the allowable values for a Tag Value. This
can only contain alphanumeric characters or special characters ( _ . : / =
+ - or @) up to 256 characters'
pUserDefinedTagKey4:
Type: String
Description: Key for user defined tag 4
AllowedPattern: ^(?!aws:)[A-Za-z0-9\s_.:=+-@/]{0,128}
ConstraintDescription: 'Must match the allowable values for a Tag Key. This can
only contain alphanumeric characters or special characters ( _ . : / = + -
or @) up to 128 characters'
pUserDefinedTagValue4:
Type: String
Description: Value for user defined tag 4
AllowedPattern: ^[\w\s_.:=+-@/]{0,256}$
ConstraintDescription: 'Must match the allowable values for a Tag Value. This
can only contain alphanumeric characters or special characters ( _ . : / =
+ - or @) up to 256 characters'
pUserDefinedTagKey5:
Type: String
Description: Key for user defined tag 5
AllowedPattern: ^(?!aws:)[A-Za-z0-9\s_.:=+-@/]{0,128}
ConstraintDescription: 'Must match the allowable values for a Tag Key. This can
only contain alphanumeric characters or special characters ( _ . : / = + -
or @) up to 128 characters'
pUserDefinedTagValue5:
Type: String
Description: Value for user defined tag 5
AllowedPattern: ^[\w\s_.:=+-@/]{0,256}$
ConstraintDescription: 'Must match the allowable values for a Tag Value. This
can only contain alphanumeric characters or special characters ( _ . : / =
+ - or @) up to 256 characters'
pVpcCidr:
Type: String
Description: CIDR block for the VPC
Default: '10.0.0.0/16'
AllowedPattern: ^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\/(1[6-9]|2[0-8]))$
ConstraintDescription: CIDR block parameter must be in the form x.x.x.x/16-28
pCDKStackName:
Type: String
Description: CDK stack name to retrieve outputs from
Default: Microservices-Microservice
pCodeConnectionArn:
Type: String
Description: Optional CodeConnection ARN for GitHub integration. If provided, will be used instead of S3 as pipeline source.
Default: ''
AllowedPattern: '^(arn:aws:codeconnections:[a-z0-9-]+:\d{12}:connection/[a-f0-9-]+)?$'
ConstraintDescription: Must be empty or a valid CodeConnection ARN
pParameterStoreBasePath:
Type: String
Description: Base path in Parameter Store for storing configuration
Default: /petstore
AllowedPattern: '^/[a-zA-Z0-9/_-]+$'
ConstraintDescription: Must be a valid Parameter Store path starting with /
pWaitForDeployment:
Type: String
Description: Wait for deployment completion using CloudFormation wait condition. Set to 'false' to mark stack complete without waiting for pipeline (useful when manually fixing pipeline issues).
Default: 'true'
AllowedValues:
- 'true'
- 'false'
ConstraintDescription: Must be either 'true' or 'false'
Conditions:
# Conditions to control creation of user-defined tags
cCreateTag1: !And
- !Not
- !Equals
- !Ref pUserDefinedTagKey1
- ''
- !Not
- !Equals
- !Ref pUserDefinedTagValue1
- ''
cCreateTag2: !And
- !Not
- !Equals
- !Ref pUserDefinedTagKey2
- ''
- !Not
- !Equals
- !Ref pUserDefinedTagValue2
- ''
cCreateTag3: !And
- !Not
- !Equals
- !Ref pUserDefinedTagKey3
- ''
- !Not
- !Equals
- !Ref pUserDefinedTagValue3
- ''
cCreateTag4: !And
- !Not
- !Equals
- !Ref pUserDefinedTagKey4
- ''
- !Not
- !Equals
- !Ref pUserDefinedTagValue4
- ''
cCreateTag5: !And
- !Not
- !Equals
- !Ref pUserDefinedTagKey5
- ''
- !Not
- !Equals
- !Ref pUserDefinedTagValue5
- ''
cWaitForDeployment: !Equals
- !Ref pWaitForDeployment
- 'true'
Resources:
# Lambda execution role for resource cleanup
rResourceCleanupRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
Policies:
- PolicyName: ResourceCleanup
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- s3:ListBucket
- s3:DeleteObject
- s3:ListBucketVersions
- s3:DeleteObjectVersion
Resource:
- !Sub ${rConfigBucket.Arn}/*
- !GetAtt rConfigBucket.Arn
# Lambda function to clean up resources
rResourceCleanupFunction:
Type: AWS::Lambda::Function
Properties:
Runtime: python3.13
Handler: index.handler
Role: !GetAtt rResourceCleanupRole.Arn
Timeout: 300
Code:
ZipFile: |
import boto3
import cfnresponse
def handler(event, context):
try:
if event['RequestType'] == 'Delete':
# Clean up S3 bucket
s3 = boto3.client('s3')
bucket = event['ResourceProperties']['BucketName']
paginator = s3.get_paginator('list_object_versions')
for page in paginator.paginate(Bucket=bucket):
delete_keys = []
if 'Versions' in page:
delete_keys.extend([{'Key': obj['Key'], 'VersionId': obj['VersionId']} for obj in page['Versions']])
if 'DeleteMarkers' in page:
delete_keys.extend([{'Key': obj['Key'], 'VersionId': obj['VersionId']} for obj in page['DeleteMarkers']])
if delete_keys:
s3.delete_objects(Bucket=bucket, Delete={'Objects': delete_keys})
cfnresponse.send(event, context, cfnresponse.SUCCESS, {})
except Exception as e:
cfnresponse.send(event, context, cfnresponse.FAILED, {}, str(e))
# Create S3 bucket to store configuration files
rConfigBucket:
Type: AWS::S3::Bucket
Properties:
VersioningConfiguration:
Status: Enabled
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
SSEAlgorithm: AES256
PublicAccessBlockConfiguration:
BlockPublicAcls: true
BlockPublicPolicy: true
IgnorePublicAcls: true
RestrictPublicBuckets: true
Tags:
- Key: Name
Value: !Sub ${AWS::StackName}-config-bucket
- !If
- cCreateTag1
- Key: !Ref pUserDefinedTagKey1
Value: !Ref pUserDefinedTagValue1
- !Ref AWS::NoValue
- !If
- cCreateTag2
- Key: !Ref pUserDefinedTagKey2
Value: !Ref pUserDefinedTagValue2
- !Ref AWS::NoValue
- !If
- cCreateTag3
- Key: !Ref pUserDefinedTagKey3
Value: !Ref pUserDefinedTagValue3
- !Ref AWS::NoValue
- !If
- cCreateTag4
- Key: !Ref pUserDefinedTagKey4
Value: !Ref pUserDefinedTagValue4
- !Ref AWS::NoValue
- !If
- cCreateTag5
- Key: !Ref pUserDefinedTagKey5
Value: !Ref pUserDefinedTagValue5
- !Ref AWS::NoValue
# Custom resource to clean up resources on deletion
rResourceCleanup:
Type: AWS::CloudFormation::CustomResource
Properties:
ServiceToken: !GetAtt rResourceCleanupFunction.Arn
BucketName: !Ref rConfigBucket
StackName: !Ref AWS::StackName
# Bucket policy to enforce HTTPS-only access
rConfigBucketPolicy:
Type: AWS::S3::BucketPolicy
Properties:
Bucket: !Ref rConfigBucket
PolicyDocument:
Statement:
- Sid: DenyInsecureConnections
Effect: Deny
Principal: '*'
Action: s3:*
Resource:
- !GetAtt rConfigBucket.Arn
- !Sub ${rConfigBucket.Arn}/*
Condition:
Bool:
aws:SecureTransport: 'false'
# Parameter Store parameter to store configuration
rWorkshopConfigParameter:
Type: AWS::SSM::Parameter
Properties:
Name: !Sub '${pParameterStoreBasePath}/${AWS::StackName}/config'
Type: String
Value: '# Configuration will be populated by CodeBuild'
Description: !Sub 'Workshop configuration for stack ${AWS::StackName}'
Tags:
Environment: workshop
StackName: !Ref AWS::StackName
# S3 bucket for CodeBuild cache
# Create IAM role for CodeBuild project
rCodeBuildServiceRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: codebuild.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- !Sub arn:${AWS::Partition}:iam::aws:policy/AdministratorAccess
Policies:
- PolicyName: EnhancedPipelineMonitoring
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- codepipeline:ListPipelineExecutions
- codepipeline:GetPipelineExecution
- codepipeline:GetPipelineState
- codepipeline:ListActionExecutions
Resource: '*'
Condition:
StringEquals:
'aws:RequestedRegion': !Ref AWS::Region
- PolicyName: ParameterStoreAccess
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- ssm:GetParameter
- ssm:GetParameters
- ssm:GetParametersByPath
- ssm:PutParameter
- ssm:DeleteParameter
Resource: !Sub 'arn:aws:ssm:${AWS::Region}:${AWS::AccountId}:parameter${pParameterStoreBasePath}/*'
Tags:
- Key: Name
Value: !Sub ${AWS::StackName}-codebuild-role
- !If
- cCreateTag1
- Key: !Ref pUserDefinedTagKey1
Value: !Ref pUserDefinedTagValue1
- !Ref AWS::NoValue
- !If
- cCreateTag2
- Key: !Ref pUserDefinedTagKey2
Value: !Ref pUserDefinedTagValue2
- !Ref AWS::NoValue
- !If
- cCreateTag3
- Key: !Ref pUserDefinedTagKey3
Value: !Ref pUserDefinedTagValue3
- !Ref AWS::NoValue
- !If
- cCreateTag4
- Key: !Ref pUserDefinedTagKey4
Value: !Ref pUserDefinedTagValue4
- !Ref AWS::NoValue
- !If
- cCreateTag5
- Key: !Ref pUserDefinedTagKey5
Value: !Ref pUserDefinedTagValue5
- !Ref AWS::NoValue
# Create wait condition handle for signaling completion
rCDKDeploymentWaitConditionHandle:
Type: AWS::CloudFormation::WaitConditionHandle
Condition: cWaitForDeployment
# Create wait condition to ensure CodeBuild project completes successfully
rCDKDeploymentWaitCondition:
Type: AWS::CloudFormation::WaitCondition
Condition: cWaitForDeployment
Properties:
Handle: !Ref rCDKDeploymentWaitConditionHandle
Timeout: 3600
Count: 1
rCDKOutputRetrieverRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- !Sub arn:${AWS::Partition}:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
Policies:
- PolicyName: CloudFormationReadAccess
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- cloudformation:DescribeStacks
- cloudformation:ListExports
Resource: '*'
rCDKOutputRetrieverFunction:
Type: AWS::Lambda::Function
Properties:
Runtime: python3.13
Handler: index.handler
Role: !GetAtt rCDKOutputRetrieverRole.Arn
Timeout: 60
Code:
ZipFile: |
import boto3
import cfnresponse
def handler(event, context):
try:
if event['RequestType'] == 'Delete':
cfnresponse.send(event, context, cfnresponse.SUCCESS, {})
return
cf = boto3.client('cloudformation')
print("Retrieving CloudFormation exports")
# Get all exports
exports = {}
paginator = cf.get_paginator('list_exports')
for page in paginator.paginate():
for export in page['Exports']:
exports[export['Name']] = export['Value']
print(f"Found {len(exports)} total exports: {list(exports.keys())}")
outputs = {}
# Find CloudFront domain for dashboard URL
for export_name, export_value in exports.items():
if 'WorkshopCloudFrontDomain' in export_name:
print(f"Found CloudFront domain: {export_name}")
cloudfront_domain = export_value if export_value.startswith('https://') else f"https://{export_value}"
outputs['ExportsDashboardUrl'] = f"{cloudfront_domain.rstrip('/')}/workshop-exports/index.html"
print(f"Dashboard URL: {outputs['ExportsDashboardUrl']}")
break
else:
print("Warning: WorkshopCloudFrontDomain export not found")
outputs['ExportsDashboardUrl'] = 'missing'
# Find PetSite URL
for export_name, export_value in exports.items():
if 'WorkshopPetSiteUrl' in export_name:
print(f"Found PetSite URL: {export_name}")
outputs['PetSiteUrl'] = export_value
break
else:
print("Warning: WorkshopPetSiteUrl export not found")
outputs['PetSiteUrl'] = 'missing'
print(f"Returning {len(outputs)} outputs")
cfnresponse.send(event, context, cfnresponse.SUCCESS, outputs)
except Exception as e:
print(f"Error: {str(e)}")
cfnresponse.send(event, context, cfnresponse.FAILED, {}, str(e))
rCDKOutputs:
Type: AWS::CloudFormation::CustomResource
Properties:
ServiceToken: !GetAtt rCDKOutputRetrieverFunction.Arn
StackName: !Ref pCDKStackName
# This ensures the custom resource waits for the wait condition if it exists
WaitConditionData: !If
- cWaitForDeployment
- !GetAtt rCDKDeploymentWaitCondition.Data
- 'NoWait'
# Create CodeBuild project to orchestrate CDK deployment
rCDKDeploymentProject:
Type: AWS::CodeBuild::Project
Properties:
Name: !Sub ${AWS::StackName}-cdk-deployment
Artifacts:
Type: NO_ARTIFACTS
Environment:
Type: LINUX_CONTAINER
ComputeType: BUILD_GENERAL1_SMALL
Image: aws/codebuild/amazonlinux2-x86_64-standard:5.0
PrivilegedMode: true
EnvironmentVariables:
- Name: APPLICATION_NAME
Value: !Ref pApplicationName
Type: PLAINTEXT
- Name: CONFIG_FILE_URL
Value: !Ref pConfigFileUrl
Type: PLAINTEXT
- Name: CONFIG_BUCKET
Value: !Ref rConfigBucket
Type: PLAINTEXT
- Name: ORGANIZATION_NAME
Value: !Ref pOrganizationName
Type: PLAINTEXT
- Name: REPOSITORY_NAME
Value: !Ref pRepositoryName
Type: PLAINTEXT
- Name: BRANCH_NAME
Value: !Ref pBranchName
Type: PLAINTEXT
- Name: WORKING_FOLDER
Value: !Ref pWorkingFolder
Type: PLAINTEXT
- Name: STACK_NAME
Value: !Ref AWS::StackName
Type: PLAINTEXT
- Name: AWS_REGION
Value: !Ref AWS::Region
Type: PLAINTEXT
- Name: AWS_ACCOUNT_ID
Value: !Ref AWS::AccountId
Type: PLAINTEXT
- Name: DISABLE_CLEANUP
Value: !Ref pDisableCleanup
Type: PLAINTEXT
- Name: VPC_CIDR
Value: !Ref pVpcCidr
Type: PLAINTEXT
- Name: CODE_CONNECTION_ARN
Value: !Ref pCodeConnectionArn
Type: PLAINTEXT
- Name: PARAMETER_STORE_BASE_PATH
Value: !Ref pParameterStoreBasePath
Type: PLAINTEXT
- Name: WAIT_FOR_DEPLOYMENT
Value: !Ref pWaitForDeployment
Type: PLAINTEXT
Cache:
Type: LOCAL
Modes:
- LOCAL_DOCKER_LAYER_CACHE
ServiceRole: !GetAtt rCodeBuildServiceRole.Arn
Source:
Type: NO_SOURCE
BuildSpec: |
version: 0.2
phases:
install:
runtime-versions:
nodejs: 22
python: 3.12
commands:
- npm install -g aws-cdk
- pip3 install git-remote-s3
pre_build:
commands:
# Configure git with generic user info
- git config --global user.email "codebuild@aws.amazon.com"
- git config --global user.name "AWS CodeBuild"
# Clone repository with shallow clone
- git clone --depth 1 --branch $BRANCH_NAME https://github.com/$ORGANIZATION_NAME/$REPOSITORY_NAME.git ./repo
- cd ./repo
# Download configuration file and create initial configuration
- |
curl -o ./config.env "$CONFIG_FILE_URL"
- cat ./config.env >> ${WORKING_FOLDER}/.env
# Run account validation script
- ./${WORKING_FOLDER}/scripts/validate-account.sh ${WORKING_FOLDER}/.env --clean
- |
CONFIG_PARAM_NAME="${PARAMETER_STORE_BASE_PATH}/${STACK_NAME}/config"
echo "Parameter path: ${CONFIG_PARAM_NAME}"
# Append additional environment variables to .env file
- |
cat >> ${WORKING_FOLDER}/.env << EOF
CONFIG_FILE_URL=$CONFIG_FILE_URL
CONFIG_BUCKET=$CONFIG_BUCKET
ORGANIZATION_NAME=$ORGANIZATION_NAME
REPOSITORY_NAME=$REPOSITORY_NAME
BRANCH_NAME=$BRANCH_NAME
WORKING_FOLDER=$WORKING_FOLDER
STACK_NAME=$STACK_NAME
AWS_REGION=$AWS_REGION
AWS_ACCOUNT_ID=$AWS_ACCOUNT_ID
DISABLE_CLEANUP=$DISABLE_CLEANUP
CODE_CONNECTION_ARN=$CODE_CONNECTION_ARN
PARAMETER_STORE_BASE_PATH=$PARAMETER_STORE_BASE_PATH
CONFIG_PARAM_NAME=$CONFIG_PARAM_NAME
EOF
# Store complete configuration in Parameter Store (parameter created by CloudFormation)
- |
echo "Storing complete configuration in Parameter Store parameter"
# Update the CloudFormation-created parameter with complete configuration
aws ssm put-parameter \
--name "${CONFIG_PARAM_NAME}" \
--value "$(cat ${WORKING_FOLDER}/.env)" \
--type "String" \
--overwrite
echo "Configuration successfully stored in Parameter Store"
echo "Configuration content:"
cat ${WORKING_FOLDER}/.env
# Handle repository source configuration based on CodeConnection ARN
- |
if [ -n "$CODE_CONNECTION_ARN" ] && [ "$CODE_CONNECTION_ARN" != "" ]; then
echo "CodeConnection ARN provided: $CODE_CONNECTION_ARN"
echo "Will use CodeConnection as pipeline source"
else
echo "No CodeConnection ARN provided, using S3 as fallback source"
# Add .env file to repository and push to S3
git add ${WORKING_FOLDER}/.env -f
git commit -m "Add merged configuration and environment variables to .env"
# Configure S3 remote with s3+zip protocol for CodePipeline
git remote add s3 s3+zip://$CONFIG_BUCKET/repo
git push s3 $BRANCH_NAME --force
fi
# Print configuration summary for troubleshooting
- |
echo "=== Configuration Summary ==="
echo "Parameter Store base path: $PARAMETER_STORE_BASE_PATH"
echo "Configuration path: ${PARAMETER_STORE_BASE_PATH}/${STACK_NAME}/config"
echo "CodeConnection ARN: ${CODE_CONNECTION_ARN:-'Not provided (using S3 fallback)'}"
echo "=== End Configuration Summary ==="
# Bootstrap current region
- ./${WORKING_FOLDER}/scripts/bootstrap-account.sh ${AWS_ACCOUNT_ID} ${AWS_REGION}
# Bootstrap us-east-1 if WAF is enabled
- |
echo "Checking for WAF configuration..."
grep "CUSTOM_ENABLE_WAF" ${WORKING_FOLDER}/.env || echo "WAF setting not found"
if grep -q "CUSTOM_ENABLE_WAF=true" ${WORKING_FOLDER}/.env; then
echo "WAF enabled, bootstrapping us-east-1..."
./${WORKING_FOLDER}/scripts/bootstrap-account.sh ${AWS_ACCOUNT_ID} us-east-1
else
echo "WAF not enabled, skipping us-east-1 bootstrap"
fi
build:
commands:
- cd $WORKING_FOLDER
# Install dependencies and synthesize CDK
- npm install
- cdk synth --quiet
# Deploy with proper tags so cleanup function can find the stack
- |
cdk deploy OneObservability \
--require-approval never \
--outputs-file cdk-outputs.json \
--tags application="$APPLICATION_NAME" \
--tags sequence="0" \
--quiet
# Extract pipeline ARN for later use
- PIPELINE_ARN=$(cat cdk-outputs.json | jq -r '.[] | select(has("PipelineArn")) | .PipelineArn')
- |
if [ -z "$PIPELINE_ARN" ] || [ "$PIPELINE_ARN" = "null" ]; then
echo "ERROR: Pipeline ARN is empty or null. CDK deployment failed to create pipeline."
exit 1
fi
- |
echo "Pipeline ARN: $PIPELINE_ARN"
- |
PIPELINE_NAME=$(echo $PIPELINE_ARN | cut -d':' -f6)
- |
echo "Pipeline Name: $PIPELINE_NAME"
# Wait for pipeline to complete
- |
./scripts/wait-for-pipeline.sh "$PIPELINE_NAME" "$STACK_NAME" "$AWS_REGION"
post_build:
commands:
- |
if [ "$CODEBUILD_BUILD_SUCCEEDING" = "0" ]; then
if [ "$DISABLE_CLEANUP" = "true" ]; then
echo "Build failed, but cleanup is disabled. Skipping resource cleanup."
else
echo "Build failed, cleaning up S3 bucket for rollback"
aws s3 rm s3://$CONFIG_BUCKET --recursive
echo "Triggering CDK stack cleanup via Step Function"
aws stepfunctions start-execution \
--state-machine-arn "arn:aws:states:$AWS_REGION:$AWS_ACCOUNT_ID:stateMachine:$STACK_NAME-cdk-cleanup" \
--input '{}' || echo "Failed to trigger cleanup, continuing..."
fi
WAIT_HANDLE_URL=$(aws cloudformation describe-stack-resource --stack-name $STACK_NAME --logical-resource-id rCDKDeploymentWaitConditionHandle --query 'StackResourceDetail.PhysicalResourceId' --output text --region $AWS_REGION)
curl -X PUT -H 'Content-Type:' --data-binary '{"Status" : "FAILURE","Reason" : "Build failed","UniqueId" : "'$(uuidgen)'","Data" : "Build execution failed"}' "$WAIT_HANDLE_URL"
else
echo "Build completed - signal already sent during pipeline monitoring"
fi
Tags:
- Key: Name
Value: !Sub ${AWS::StackName}-cdk-deployment
- !If
- cCreateTag1
- Key: !Ref pUserDefinedTagKey1
Value: !Ref pUserDefinedTagValue1
- !Ref AWS::NoValue
- !If
- cCreateTag2
- Key: !Ref pUserDefinedTagKey2
Value: !Ref pUserDefinedTagValue2
- !Ref AWS::NoValue
- !If
- cCreateTag3
- Key: !Ref pUserDefinedTagKey3
Value: !Ref pUserDefinedTagValue3
- !Ref AWS::NoValue
- !If
- cCreateTag4
- Key: !Ref pUserDefinedTagKey4
Value: !Ref pUserDefinedTagValue4
- !Ref AWS::NoValue
- !If
- cCreateTag5
- Key: !Ref pUserDefinedTagKey5
Value: !Ref pUserDefinedTagValue5
- !Ref AWS::NoValue
# Start the CodeBuild project to begin deployment
rStartDeployment:
Type: Custom::StartDeployment
DependsOn:
- rConfigBucket
- rCodeBuildServiceRole
Properties:
ServiceToken: !GetAtt rStartDeploymentFunction.Arn
CodeBuildProjectName: !Ref rCDKDeploymentProject
WaitConditionHandle: !If
- cWaitForDeployment
- !Ref rCDKDeploymentWaitConditionHandle
- !Ref AWS::NoValue
# Create Lambda function to start the CodeBuild project
rStartDeploymentFunction:
Type: AWS::Lambda::Function
Properties:
Runtime: python3.13
Handler: index.handler
Role: !GetAtt rStartDeploymentFunctionRole.Arn
Code:
ZipFile: |
import boto3
import cfnresponse
import time
def handler(event, context):
if event['RequestType'] in ['Create', 'Update']:
try:
codebuild = boto3.client('codebuild')
project_name = event['ResourceProperties']['CodeBuildProjectName']
# Start the CodeBuild project
response = codebuild.start_build(projectName=project_name)
build_id = response['build']['id']
# Wait a few seconds to ensure the build starts
time.sleep(5)
cfnresponse.send(event, context, cfnresponse.SUCCESS, {
'BuildId': build_id
})
except Exception as e:
print(f"Error starting CodeBuild project: {str(e)}")
cfnresponse.send(event, context, cfnresponse.FAILED, {
'Error': str(e)
})
else: # Delete
cfnresponse.send(event, context, cfnresponse.SUCCESS, {})
Timeout: 30
Tags:
- Key: Name
Value: !Sub ${AWS::StackName}-start-deployment-function
- !If
- cCreateTag1
- Key: !Ref pUserDefinedTagKey1
Value: !Ref pUserDefinedTagValue1
- !Ref AWS::NoValue
- !If
- cCreateTag2
- Key: !Ref pUserDefinedTagKey2
Value: !Ref pUserDefinedTagValue2
- !Ref AWS::NoValue
- !If
- cCreateTag3
- Key: !Ref pUserDefinedTagKey3
Value: !Ref pUserDefinedTagValue3
- !Ref AWS::NoValue
- !If
- cCreateTag4
- Key: !Ref pUserDefinedTagKey4
Value: !Ref pUserDefinedTagValue4
- !Ref AWS::NoValue
- !If
- cCreateTag5
- Key: !Ref pUserDefinedTagKey5
Value: !Ref pUserDefinedTagValue5
- !Ref AWS::NoValue
# Create IAM role for start deployment Lambda function
rStartDeploymentFunctionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- !Sub arn:${AWS::Partition}:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
Policies:
- PolicyName: CodeBuildAccess
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- codebuild:StartBuild
Resource: !GetAtt rCDKDeploymentProject.Arn
Tags:
- Key: Name
Value: !Sub ${AWS::StackName}-start-deployment-role
- !If
- cCreateTag1
- Key: !Ref pUserDefinedTagKey1
Value: !Ref pUserDefinedTagValue1
- !Ref AWS::NoValue
- !If
- cCreateTag2
- Key: !Ref pUserDefinedTagKey2
Value: !Ref pUserDefinedTagValue2
- !Ref AWS::NoValue
- !If
- cCreateTag3
- Key: !Ref pUserDefinedTagKey3
Value: !Ref pUserDefinedTagValue3
- !Ref AWS::NoValue
- !If
- cCreateTag4
- Key: !Ref pUserDefinedTagKey4
Value: !Ref pUserDefinedTagValue4
- !Ref AWS::NoValue
- !If
- cCreateTag5
- Key: !Ref pUserDefinedTagKey5
Value: !Ref pUserDefinedTagValue5
- !Ref AWS::NoValue
# Step Function for CDK Stack Cleanup
rCDKCleanupStateMachine:
Type: AWS::StepFunctions::StateMachine
Properties:
StateMachineName: !Sub ${AWS::StackName}-cdk-cleanup
RoleArn: !GetAtt rCDKCleanupRole.Arn
DefinitionString: !Sub |
{
"Comment": "CDK Stack Cleanup State Machine",
"StartAt": "ListTaggedStacks",
"States": {
"ListTaggedStacks": {
"Type": "Task",
"Resource": "arn:aws:states:::lambda:invoke",
"Parameters": {
"FunctionName": "${rCDKStackListerFunction}",
"Payload": {}
},
"ResultPath": "$.stackList",
"Next": "CheckStacksFound"
},
"CheckStacksFound": {
"Type": "Choice",
"Choices": [
{
"Variable": "$.stackList.Payload.stacks",
"IsPresent": true,
"Next": "DeleteStacks"
}
],
"Default": "CleanupCDKStagingBucket"
},
"DeleteStacks": {
"Type": "Map",
"ItemsPath": "$.stackList.Payload.stacks",
"MaxConcurrency": 1,