-
Notifications
You must be signed in to change notification settings - Fork 0
/
cicd.yaml
966 lines (954 loc) · 29.7 KB
/
cicd.yaml
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
AWSTemplateFormatVersion: 2010-09-09
Description: CI/CD infrastructure for a simple calculator application
Parameters:
codeBucket:
Description: S3 Bucket where functions.zip and calculator.zip are stored.
Type: String
EnvironmentName:
Description: An environment name that will be prefixed to resource names
Type: String
Default: CI-CD
VpcCIDR:
Description: IP range (CIDR notation) for the VPC
Type: String
Default: 192.168.0.0/16
AllowedPattern: ^([0-9]{1,3}\.){3}[0-9]{1,3}(\/([1][6-9]|[2][0-8]))$
PublicSubnet1CIDR:
Description: IP range (CIDR notation) for the PUBLIC subnet in the FIRST Availability Zone
Type: String
Default: 192.168.0.0/20
AllowedPattern: ^([0-9]{1,3}\.){3}[0-9]{1,3}(\/([1][6-9]|[2][0-8]))$
PrivateSubnet1CIDR:
Description: IP range (CIDR notation) for the PRIVATE subnet in the SECOND Availability Zone
Type: String
Default: 192.168.64.0/20
AllowedPattern: ^([0-9]{1,3}\.){3}[0-9]{1,3}(\/([1][6-9]|[2][0-8]))$
PublicSubnet2CIDR:
Description: IP range (CIDR notation) for the PUBLIC subnet in the SECOND Availability Zone
Type: String
Default: 192.168.16.0/20
AllowedPattern: ^([0-9]{1,3}\.){3}[0-9]{1,3}(\/([1][6-9]|[2][0-8]))$
ApplicationName:
Description: An application name that will be prefixed to resource names
Type: String
Default: simple-calculator
LatestAmiId:
Description: The AWS::EC2::Image::Id that will be pulled from AWS System Manager parameter store (Publicly Available on AWS) to be used for application instances
Type: AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>
Default: /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-6.1-x86_64
OutputsPrefix:
Description: The prefix for stack outputs that will be used for the pipeline resources
Type: String
Default: shared-resources
Metadata:
# Parameter formatting to help explain what parameters need to be changed.
# codeBucket is the only parameter not having a default value because in this project I
# create the S3 bucket and upload the files (functions.zip and calculator.zip) into it using the
# AWS CLI from my AWS Cloudshell (You can access and use it in your browser from your management console)
AWS::CloudFormation::Interface:
ParameterGroups:
- Label:
default: Required Parameters
Parameters:
- codeBucket
- Label:
default: Other Parameters
Parameters:
- EnvironmentName
- VpcCIDR
- PublicSubnet1CIDR
- PublicSubnet2CIDR
- PrivateSubnet1CIDR
- ApplicationName
- LatestAmiId
- OutputsPrefix
ParameterLabels:
codeBucket:
default: Bucket where functions.zip and calculator.zip are stored
EnvironmentName:
default: An environment name that will be prefixed to resource names
VpcCIDR:
default: IP range (CIDR notation) for the VPC
PublicSubnet1CIDR:
default: IP range (CIDR notation) for the PUBLIC subnet in the FIRST Availability Zone
PublicSubnet2CIDR:
default: IP range (CIDR notation) for the PUBLIC subnet in the SECOND Availability Zone
PrivateSubnet1CIDR:
default: IP range (CIDR notation) for the PRIVATE subnet in the SECOND Availability Zone
ApplicationName:
default: An application name that will be prefixed to resource names
LatestAmiId:
default: The AWS::EC2::Image::Id that will be pulled from parameter store to be used for application instances
OutputsPrefix:
default: The prefix for stack outputs that will be used for your pipeline resources
Resources:
# Code Repository for the simple Calculator application (CodeCommit Repo)
CodeCommitRepo:
Type: AWS::CodeCommit::Repository
Properties:
RepositoryName: !Ref EnvironmentName
RepositoryDescription: Calculator application repository
Code:
S3:
Bucket: !Sub ${codeBucket}
Key: calculator.zip
# Shared Network Resources for the application environments (Test & Prod)
VPC:
Type: AWS::EC2::VPC
Properties:
CidrBlock: !Ref VpcCIDR
EnableDnsSupport: true
EnableDnsHostnames: true
Tags:
- Key: Name
Value: !Sub ${EnvironmentName} VPC
InternetGateway:
Type: AWS::EC2::InternetGateway
Properties:
Tags:
- Key: Name
Value: !Sub ${EnvironmentName} IG
InternetGatewayAttachment:
Type: AWS::EC2::VPCGatewayAttachment
Properties:
InternetGatewayId: !Ref InternetGateway
VpcId: !Ref VPC
PublicSubnet1:
Type: AWS::EC2::Subnet
Properties:
VpcId: !Ref VPC
AvailabilityZone:
Fn::Select:
- 0
- Fn::GetAZs: ""
CidrBlock: !Ref PublicSubnet1CIDR
MapPublicIpOnLaunch: true
Tags:
- Key: Name
Value: !Sub ${EnvironmentName} Public Subnet 1
PublicSubnet2:
Type: AWS::EC2::Subnet
Properties:
VpcId: !Ref VPC
AvailabilityZone:
Fn::Select:
- 1
- Fn::GetAZs: ""
CidrBlock: !Ref PublicSubnet2CIDR
MapPublicIpOnLaunch: true
Tags:
- Key: Name
Value: !Sub ${EnvironmentName} Public Subnet 2
PrivateSubnet1:
Type: AWS::EC2::Subnet
Properties:
VpcId: !Ref VPC
AvailabilityZone:
Fn::Select:
- 0
- Fn::GetAZs: ""
CidrBlock: !Ref PrivateSubnet1CIDR
MapPublicIpOnLaunch: false
Tags:
- Key: Name
Value: !Sub ${ApplicationName} Private Subnet 1
NatGateway1EIP:
Type: AWS::EC2::EIP
DependsOn: InternetGatewayAttachment
Properties:
Domain: vpc
NatGateway1:
Type: AWS::EC2::NatGateway
Properties:
AllocationId: !GetAtt NatGateway1EIP.AllocationId
SubnetId: !Ref PublicSubnet2
PublicRouteTable:
Type: AWS::EC2::RouteTable
Properties:
VpcId: !Ref VPC
Tags:
- Key: Name
Value: !Sub ${EnvironmentName} Public Routes
DefaultPublicRoute:
Type: AWS::EC2::Route
DependsOn: InternetGatewayAttachment
Properties:
RouteTableId: !Ref PublicRouteTable
DestinationCidrBlock: 0.0.0.0/0
GatewayId: !Ref InternetGateway
PublicSubnet1RouteTableAssociation:
Type: AWS::EC2::SubnetRouteTableAssociation
Properties:
RouteTableId: !Ref PublicRouteTable
SubnetId: !Ref PublicSubnet1
PublicSubnet2RouteTableAssociation:
Type: AWS::EC2::SubnetRouteTableAssociation
Properties:
RouteTableId: !Ref PublicRouteTable
SubnetId: !Ref PublicSubnet2
PrivateRouteTable1:
Type: AWS::EC2::RouteTable
Properties:
VpcId: !Ref VPC
Tags:
- Key: Name
Value: !Sub ${ApplicationName} Private Routes 1
DefaultPrivateRoute1:
Type: AWS::EC2::Route
Properties:
RouteTableId: !Ref PrivateRouteTable1
DestinationCidrBlock: 0.0.0.0/0
NatGatewayId: !Ref NatGateway1
PrivateSubnet1RouteTableAssociation:
Type: AWS::EC2::SubnetRouteTableAssociation
Properties:
RouteTableId: !Ref PrivateRouteTable1
SubnetId: !Ref PrivateSubnet1
PublicHttpIngressSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Security group that allows HTTP ingress from internet
GroupName: public-http-ingress-sg
VpcId: !Ref VPC
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 80
ToPort: 80
CidrIp: 0.0.0.0/0
PrivateHttpIngressSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupName: private-http-ingress-sg
GroupDescription: Security group that allows HTTP ingress from load balancer
VpcId: !Ref VPC
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 8080
ToPort: 8080
SourceSecurityGroupId:
Ref: PublicHttpIngressSecurityGroup
# CodeBuild Project to build the application and run unit tests
CodeBuildProject:
DependsOn:
- CodeBuildPolicy
Properties:
Artifacts:
Location: !Ref ArtifactsBucket
Name: build-output.zip
NamespaceType: BUILD_ID
Packaging: ZIP
Path: codebuild
Type: S3
Cache:
Location: !Ref CacheBucket
Type: S3
Description: !Sub CodeBuild Project for ${AWS::StackName}
Environment:
ComputeType: BUILD_GENERAL1_SMALL
Image: aws/codebuild/nodejs:8.11.0
Type: LINUX_CONTAINER
Name: !Ref AWS::StackName
ServiceRole: !Ref CodeBuildRole
Source:
Type: CODECOMMIT
Location: !GetAtt CodeCommitRepo.CloneUrlHttp
BuildSpec: buildspec.yml
Type: AWS::CodeBuild::Project
# IAM Resources for the CI/CD pipeline
CloudFormationTrustRole:
Properties:
AssumeRolePolicyDocument:
Statement:
- Action: sts:AssumeRole
Effect: Allow
Principal:
Service:
- cloudformation.amazonaws.com
Path: /
Policies:
- PolicyDocument:
Statement:
- Action:
- iam:CreateInstanceProfile
- iam:DeleteInstanceProfile
- iam:GetRole
- iam:GetInstanceProfile
- iam:RemoveRoleFromInstanceProfile
- iam:UpdateRoleDescription
- iam:CreateRole
- iam:DeleteRole
- iam:AttachRolePolicy
- iam:PutRolePolicy
- iam:ListInstanceProfiles
- iam:AddRoleToInstanceProfile
- iam:ListInstanceProfilesForRole
- iam:PassRole
- iam:DetachRolePolicy
- iam:DeleteRolePolicy
- iam:ListRolePolicies
- iam:ListRoles
- iam:GetRolePolicy
Effect: Allow
Resource:
- !Sub arn:aws:iam::*:role/${AWS::StackName}*
- !Sub arn:aws:iam::*:instance-profile/${AWS::StackName}*
- Action:
- iam:CreateServiceLinkedRole
Effect: Allow
Resource:
- arn:aws:iam::*:role/aws-service-role/*
- Action:
- ssm:GetParameters
- autoscaling:*
- ec2:*
- codedeploy:*
- elasticloadbalancing:*
Effect: Allow
Resource:
- "*"
PolicyName: !Sub ${AWS::StackName}-CloudFormationRolePolicy
RoleName: !Sub ${AWS::StackName}-CloudFormation
Type: AWS::IAM::Role
LambdaCodePipelineExecutionPolicy:
DependsOn:
- CloudFormationTrustRole
Type: AWS::IAM::Policy
Properties:
PolicyName: LambdaRolePolicy
Roles:
- !Ref CodePipelineLambdaRole
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- logs:*
Resource:
- arn:aws:logs:*:*:*
- Effect: Allow
Action:
- codepipeline:PutJobSuccessResult
- codepipeline:PutJobFailureResult
- s3:*
- ec2:*
- cloudformation:*
Resource:
- "*"
- Effect: Allow
Action:
- dynamodb:*
Resource:
- "*"
CodeBuildPolicy:
Properties:
PolicyDocument:
Statement:
- Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Effect: Allow
Resource: "*"
- Action:
- s3:PutObject
- s3:GetObject
- s3:GetObjectVersion
Effect: Allow
Resource:
- !GetAtt ArtifactsBucket.Arn
- !Sub ${ArtifactsBucket.Arn}/*
- !GetAtt CacheBucket.Arn
- !Sub ${CacheBucket.Arn}/*
- Action:
- codecommit:GitPull
Effect: Allow
Resource: !GetAtt CodeCommitRepo.Arn
- Action:
- kms:GenerateDataKey*
- kms:Encrypt
- kms:Decrypt
Effect: Allow
Resource: !Sub arn:aws:kms:${AWS::Region}:${AWS::AccountId}:alias/aws/s3
PolicyName: !Sub ${AWS::StackName}-CodeBuildPolicy
Roles:
- !Ref CodeBuildRole
Type: AWS::IAM::Policy
CodeBuildRole:
Properties:
AssumeRolePolicyDocument:
Statement:
- Action: sts:AssumeRole
Effect: Allow
Principal:
Service: codebuild.amazonaws.com
Path: /
RoleName: !Sub ${AWS::StackName}-CodeBuild
Type: AWS::IAM::Role
CodePipelineLambdaRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
Path: /
CodePipelineTrustRole:
Properties:
AssumeRolePolicyDocument:
Statement:
- Action: sts:AssumeRole
Effect: Allow
Principal:
Service:
- codepipeline.amazonaws.com
Sid: 1
Path: /
Policies:
- PolicyDocument:
Statement:
- Action:
- s3:GetObject
- s3:GetObjectVersion
- s3:GetBucketVersioning
- s3:PutObject
Effect: Allow
Resource:
- !GetAtt ArtifactsBucket.Arn
- !Sub ${ArtifactsBucket.Arn}/*
- Action:
- codecommit:CancelUploadArchive
- codecommit:GetBranch
- codecommit:GetCommit
- codecommit:GetUploadArchiveStatus
- codecommit:UploadArchive
Effect: Allow
Resource:
- !GetAtt CodeCommitRepo.Arn
- Action:
- codebuild:StartBuild
- codebuild:BatchGetBuilds
- codebuild:StopBuild
Effect: Allow
Resource:
- !GetAtt CodeBuildProject.Arn
- Action:
- codedeploy:CreateDeployment
- codedeploy:GetApplicationRevision
- codedeploy:GetDeployment
- codedeploy:GetDeploymentConfig
- codedeploy:RegisterApplicationRevision
Effect: Allow
Resource:
- !Sub arn:aws:codedeploy:${AWS::Region}:${AWS::AccountId}:deploymentgroup:${AWS::StackName}*
- !Sub arn:aws:codedeploy:${AWS::Region}:${AWS::AccountId}:application:${AWS::StackName}*
- !Sub arn:aws:codedeploy:${AWS::Region}:${AWS::AccountId}:deploymentconfig:*
- Action:
- cloudformation:CreateStack
- cloudformation:DescribeStacks
- cloudformation:DescribeStackEvents
- cloudformation:DeleteStack
- cloudformation:UpdateStack
- cloudformation:CreateChangeSet
- cloudformation:ExecuteChangeSet
- cloudformation:DeleteChangeSet
- cloudformation:DescribeChangeSet
- cloudformation:SetStackPolicy
Effect: Allow
Resource:
- !Sub arn:aws:cloudformation:${AWS::Region}:${AWS::AccountId}:stack/${AWS::StackName}*
- Action:
- iam:PassRole
Effect: Allow
Resource:
- !GetAtt CloudFormationTrustRole.Arn
- Action:
- lambda:InvokeFunction
Effect: Allow
Resource: "*"
PolicyName: !Sub ${AWS::StackName}-CodePipelineRolePolicy
RoleName: !Sub ${AWS::StackName}-CodePipeline
Type: AWS::IAM::Role
CodeDeployRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- codedeploy.amazonaws.com
Action:
- sts:AssumeRole
Policies:
- PolicyName: allow-autoscaling
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- ec2:*
- autoscaling:*
Resource: "*"
InstanceRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- ec2.amazonaws.com
- codedeploy.amazonaws.com
Action:
- sts:AssumeRole
Policies:
- PolicyName: allow-deployment-bucket
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- s3:GetObject
- s3:GetObjectVersion
Resource:
- !Sub ${ArtifactsBucket.Arn}/*
InstanceProfile:
Type: AWS::IAM::InstanceProfile
Properties:
Roles:
- Ref: InstanceRole
LambdaExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
Path: /
Policies:
- PolicyName: !Sub lambdaLogsCreatePolicy-${AWS::StackName}
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- logs:CreateLogGroup
Resource: !Sub arn:aws:logs:${AWS::Region}:${AWS::AccountId}:*
- PolicyName: !Sub lambdaLogPolicy-${AWS::StackName}
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- logs:CreateLogStream
- logs:PutLogEvents
Resource:
- !Sub arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/*:*
SourceEventRole:
Properties:
AssumeRolePolicyDocument:
Statement:
- Action: sts:AssumeRole
Effect: Allow
Principal:
Service:
- events.amazonaws.com
Sid: 1
Path: /
Policies:
- PolicyDocument:
Statement:
- Action:
- codepipeline:StartPipelineExecution
Effect: Allow
Resource:
- !Sub arn:aws:codepipeline:${AWS::Region}:${AWS::AccountId}:${EnvironmentName}-releasePipeline
PolicyName: !Sub ${EnvironmentName}-CloudWatchEventPolicy
RoleName: !Sub ${EnvironmentName}-CloudWatchEventRule
Type: AWS::IAM::Role
# Static Code Analysis Lambda function
CFNValidateLambda:
Type: AWS::Lambda::Function
DependsOn:
- LambdaCodePipelineExecutionPolicy
- DBRules
Properties:
Code:
S3Bucket: !Ref codeBucket
S3Key: functions.zip
Role: !GetAtt CodePipelineLambdaRole.Arn
Description: Checks the CloudFormation template for known violations
Timeout: 60
Handler: cfn_validate_lambda.lambda_handler
Runtime: python3.8
TracingConfig:
Mode: Active
# Service Status Lambda function for synthetic testing
servicestatus:
Type: AWS::Lambda::Function
DependsOn:
- LambdaCodePipelineExecutionPolicy
Properties:
Code:
S3Bucket: !Ref codeBucket
S3Key: functions.zip
Role: !GetAtt CodePipelineLambdaRole.Arn
Description: Test to check url passed in the event for a 200 status code
Timeout: 60
Handler: index.handler
Runtime: nodejs16.x
TracingConfig:
Mode: Active
# S3 Buckets and policy to hold build artifacts
ArtifactBucketPolicy:
Properties:
Bucket: !Ref ArtifactsBucket
PolicyDocument:
Id: SSEAndSSLPolicy
Statement:
- Action:
- s3:GetObject
- s3:GetObjectVersion
- s3:GetBucketVersioning
Condition:
Bool:
aws:SecureTransport: false
Effect: Allow
Principal:
AWS:
- !GetAtt CodePipelineTrustRole.Arn
- !GetAtt CodeBuildRole.Arn
- !GetAtt CloudFormationTrustRole.Arn
Resource:
- !GetAtt ArtifactsBucket.Arn
- !Sub ${ArtifactsBucket.Arn}/*
Sid: WhitelistedGet
- Action:
- s3:PutObject
Effect: Allow
Principal:
AWS:
- !GetAtt CodePipelineTrustRole.Arn
- !GetAtt CodeBuildRole.Arn
Resource:
- !GetAtt ArtifactsBucket.Arn
- !Sub ${ArtifactsBucket.Arn}/*
Sid: WhitelistedPut
Version: 2012-10-17
Type: AWS::S3::BucketPolicy
ArtifactsBucket:
Type: AWS::S3::Bucket
DeletionPolicy: Delete
Properties:
LifecycleConfiguration:
Rules:
- ExpirationInDays: 7
Status: Enabled
CacheBucket:
DeletionPolicy: Delete
Properties:
LifecycleConfiguration:
Rules:
- ExpirationInDays: 3
Status: Enabled
Type: AWS::S3::Bucket
# Dynamodb table for static code analysis rules
DBRules:
Type: AWS::DynamoDB::Table
Properties:
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: rule
AttributeType: S
KeySchema:
- AttributeName: rule
KeyType: HASH
# CodeDeploy Application to install the application to ec2 instances
CodeDeployApplication:
Properties:
ApplicationName: !Ref AWS::StackName
Type: AWS::CodeDeploy::Application
# Launch config for launching environment instances
LaunchConfig:
Type: AWS::AutoScaling::LaunchConfiguration
Properties:
AssociatePublicIpAddress: false
ImageId: !Ref LatestAmiId
InstanceType: t2.micro
SecurityGroups:
- Ref: PrivateHttpIngressSecurityGroup
IamInstanceProfile:
Ref: InstanceProfile
UserData:
Fn::Base64: !Sub |
#!/bin/bash
yum -y update
yum install -y ruby
cd /home/ec2-user
curl -O https://aws-codedeploy-${AWS::Region}.s3.amazonaws.com/latest/install
chmod +x ./install
./install auto
# CodePipeline resources & CloudWatch Events rule to kickoff the pipeline when code changes
SourceEvent:
Properties:
Description: >-
Rule for Amazon CloudWatch Events to detect changes to the source repository and trigger pipeline execution
EventPattern:
detail:
event:
- referenceCreated
- referenceUpdated
referenceName:
- main
referenceType:
- branch
detail-type:
- CodeCommit Repository State Change
resources:
- !GetAtt CodeCommitRepo.Arn
source:
- aws.codecommit
Name: !Sub ${EnvironmentName}-SourceEvent
State: ENABLED
Targets:
- Arn: !Sub arn:aws:codepipeline:${AWS::Region}:${AWS::AccountId}:${EnvironmentName}-releasePipeline
Id: ProjectPipelineTarget
RoleArn: !GetAtt SourceEventRole.Arn
Type: AWS::Events::Rule
# CodePipeline pipeline ;)
ReleasePipeline:
Type: AWS::CodePipeline::Pipeline
Properties:
Name: !Sub ${EnvironmentName}-releasePipeline
ArtifactStore:
Location: !Ref ArtifactsBucket
Type: S3
RoleArn: !GetAtt CodePipelineTrustRole.Arn
Stages:
- Name: Source
Actions:
- ActionTypeId:
Category: Source
Owner: AWS
Provider: CodeCommit
Version: 1
Configuration:
BranchName: main
PollForSourceChanges: false
RepositoryName: !GetAtt CodeCommitRepo.Name
InputArtifacts: []
Name: ApplicationSource
OutputArtifacts:
- Name: !Sub ${AWS::StackName}-SourceArtifact
RunOrder: 1
- Name: Static_Check
Actions:
- ActionTypeId:
Category: Invoke
Owner: AWS
Provider: Lambda
Version: 1
Configuration:
FunctionName: !Ref CFNValidateLambda
UserParameters: !Sub "{\"input\": \"${AWS::StackName}-SourceArtifact\", \n\"file\": \"cloudformation/application.json\",\n\"output\": \"${ArtifactsBucket}\"}\n"
InputArtifacts:
- Name: !Sub ${AWS::StackName}-SourceArtifact
OutputArtifacts:
- Name: TemplateSource2
Name: stack_validate
Region: !Ref AWS::Region
RunOrder: 1
- Name: Build
Actions:
- ActionTypeId:
Category: Build
Owner: AWS
Provider: CodeBuild
Version: 1
Configuration:
ProjectName: !Ref AWS::StackName
InputArtifacts:
- Name: !Sub ${AWS::StackName}-SourceArtifact
Name: Build
OutputArtifacts:
- Name: !Sub ${AWS::StackName}-BuildArtifact
RunOrder: 1
- Name: Test_Stack
Actions:
- ActionTypeId:
Category: Deploy
Owner: AWS
Provider: CloudFormation
Version: 1
Configuration:
ActionMode: CHANGE_SET_REPLACE
Capabilities: CAPABILITY_IAM
ChangeSetName: test-stack-changeset
ParameterOverrides: '{"Stage": "Test"}'
RoleArn: !GetAtt CloudFormationTrustRole.Arn
StackName: !Sub ${AWS::StackName}-test-stack
TemplatePath: !Sub ${AWS::StackName}-BuildArtifact::cloudformation/application.json
InputArtifacts:
- Name: !Sub ${AWS::StackName}-BuildArtifact
Name: GenerateChangeSet
RunOrder: 1
- ActionTypeId:
Category: Deploy
Owner: AWS
Provider: CloudFormation
Version: 1
Configuration:
ActionMode: CHANGE_SET_EXECUTE
ChangeSetName: test-stack-changeset
StackName: !Sub ${AWS::StackName}-test-stack
InputArtifacts: []
Name: ExecuteChangeSet
Namespace: TestStackOutput
RunOrder: 2
- ActionTypeId:
Category: Deploy
Owner: AWS
Provider: CodeDeploy
Version: 1
Configuration:
ApplicationName: !Ref AWS::StackName
DeploymentGroupName: !Sub ${AWS::StackName}-test-stack-DeploymentGroup
InputArtifacts:
- Name: !Sub ${AWS::StackName}-BuildArtifact
Name: Deploy
OutputArtifacts: []
RunOrder: 3
- Name: Service_Status
Actions:
- ActionTypeId:
Category: Invoke
Owner: AWS
Provider: Lambda
Version: 1
Configuration:
FunctionName: !Ref servicestatus
UserParameters: '#{TestStackOutput.Url}'
Name: Test_Status
Region: !Ref AWS::Region
RunOrder: 1
- Name: Approval
Actions:
- ActionTypeId:
Category: Approval
Owner: AWS
Provider: Manual
Version: 1
Configuration:
CustomData: >-
Do you want to purge Test region resources and initiate Production deployment?
InputArtifacts: []
Name: Purge_Test
OutputArtifacts: []
Region: !Ref AWS::Region
RunOrder: 1
- ActionTypeId:
Category: Deploy
Owner: AWS
Provider: CloudFormation
Version: 1
Configuration:
ActionMode: DELETE_ONLY
RoleArn: !GetAtt CloudFormationTrustRole.Arn
StackName: !Sub ${AWS::StackName}-test-stack
InputArtifacts: []
Name: Delete_Test_Stack
OutputArtifacts: []
Region: !Ref AWS::Region
RunOrder: 2
- Name: Prod_Stack
Actions:
- ActionTypeId:
Category: Deploy
Owner: AWS
Provider: CloudFormation
Version: 1
Configuration:
ActionMode: CHANGE_SET_REPLACE
Capabilities: CAPABILITY_IAM
ChangeSetName: prod-stack-changeset
ParameterOverrides: '{"Stage": "Prod"}'
RoleArn: !GetAtt CloudFormationTrustRole.Arn
StackName: !Sub ${AWS::StackName}-prod-stack
TemplatePath: !Sub ${AWS::StackName}-BuildArtifact::cloudformation/application.json
InputArtifacts:
- Name: !Sub ${AWS::StackName}-BuildArtifact
Name: GenerateChangeSet
OutputArtifacts: []
RunOrder: 1
- ActionTypeId:
Category: Deploy
Owner: AWS
Provider: CloudFormation
Version: 1
Configuration:
ActionMode: CHANGE_SET_EXECUTE
ChangeSetName: prod-stack-changeset
StackName: !Sub ${AWS::StackName}-prod-stack
InputArtifacts: []
Name: ExecuteChangeSet
OutputArtifacts: []
RunOrder: 2
- ActionTypeId:
Category: Deploy
Owner: AWS
Provider: CodeDeploy
Version: 1
Configuration:
ApplicationName: !Ref AWS::StackName
DeploymentGroupName: !Sub ${AWS::StackName}-prod-stack-DeploymentGroup
InputArtifacts:
- Name: !Sub ${AWS::StackName}-BuildArtifact
Name: Deploy
OutputArtifacts: []
RunOrder: 3
Outputs:
# Outputs that are used by the application environment cloudformation template
vpc:
Value: !Ref VPC
Export:
Name: !Sub ${OutputsPrefix}:VPC
publicsubnets:
Value: !Sub ${PublicSubnet1},${PublicSubnet2}
Export:
Name: !Sub ${OutputsPrefix}:PublicSubnets
privatesubnets:
Value: !Sub ${PrivateSubnet1}
Export:
Name: !Sub ${OutputsPrefix}:PrivateSubnets
publichttpingresssecuritygroup:
Value: !Ref PublicHttpIngressSecurityGroup
Export:
Name: !Sub ${OutputsPrefix}:PublicHttpIngressSecurityGroup
launchconfig:
Value: !Ref LaunchConfig
Export:
Name: !Sub ${OutputsPrefix}:LaunchConfig
codedeployapplication:
Value: !Ref CodeDeployApplication
Export:
Name: !Sub ${OutputsPrefix}:CodeDeployApplication
applicationname:
Value: !Ref ApplicationName
Export:
Name: !Sub ${OutputsPrefix}:ApplicationName
codedeployrole:
Value: !GetAtt CodeDeployRole.Arn
Export:
Name: !Sub ${OutputsPrefix}:CodeDeployRole