This repository has been archived by the owner on Oct 4, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 114
/
Copy pathgit2s3.template.yaml
995 lines (965 loc) · 33.7 KB
/
git2s3.template.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
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
AWSTemplateFormatVersion: '2010-09-09'
Description: Git webhooks to clone and store a Git repository in S3. Used to integrate Git services
with AWS services like AWS CodePipeline, AWS CodeBuild, and AWS CodeDeploy. (qs-1nfhrd9bh)
Metadata:
QuickStartDocumentation:
EntrypointName: Parameters for deploying into your selected Region
AWS::CloudFormation::Interface:
ParameterGroups:
- Label:
default: General settings
Parameters:
- OutputBucketName
- CustomDomainName
- Label:
default: Git pull settings
Parameters:
- ApiSecret
- AllowedIps
- ExcludeGit
- Label:
default: AWS Quick Start configuration
Parameters:
- QSS3BucketName
- QSS3BucketRegion
- QSS3KeyPrefix
- Label:
default: VPC configuration
Parameters:
- VPCId
- VPCCidrRange
- SubnetIds
- ScmHostnameOverride
ParameterLabels:
AllowedIps:
default: Allowed IP addresses
ApiSecret:
default: API secret
CustomDomainName:
default: Custom domain name
OutputBucketName:
default: Output S3 bucket name
QSS3BucketName:
default: Quick Start S3 bucket name
QSS3BucketRegion:
default: Quick Start S3 bucket Region
QSS3KeyPrefix:
default: Quick Start S3 key prefix
VPCId:
default: VPC ID
VPCCidrRange:
default: VPC CIDR
SubnetIds:
default: Subnet IDs
ScmHostnameOverride:
default: Hostname override
ExcludeGit:
default: Exclude .git directory
Parameters:
AllowedIps:
Description: Comma-separated list of allowed IP CIDR blocks. The default addresses listed are BitBucket Cloud IP ranges.
Type: String
Default: 18.205.93.0/25,18.234.32.128/25,13.52.5.0/25
ApiSecret:
Description: API secret used to authenticate access to webhooks in GitHub Enterprise, GitLab, and other Git services. If a webhook payload header contains a matching secret, IP address authentication is bypassed. API secrets cannot contain commas (,), backward slashes (\), or quotes (").
Type: String
Default: ''
NoEcho: 'true'
CustomDomainName:
Description: Domain name for the webhook endpoint. If left blank, API Gateway creates a domain name for you.
Type: String
Default: ''
OutputBucketName:
Description: (Optional) Name for the S3 bucket where the Git repository .zip file is stored. If left blank, the Quick Start creates one for you.
Type: String
Default: ''
QSS3BucketName:
AllowedPattern: ^[0-9a-zA-Z]+([0-9a-zA-Z-]*[0-9a-zA-Z])*$
ConstraintDescription: Quick Start S3 bucket name can include numbers, lowercase letters, uppercase letters, and hyphens (-). It cannot start or end with a hyphen
(-).
Default: aws-quickstart
Description: S3 bucket name for Quick Start assets. It can include numbers, lowercase letters, uppercase letters, and hyphens (-). It cannot start or end with a hyphen (-).
Type: String
QSS3BucketRegion:
Default: 'us-east-1'
Description: AWS Region where the Quick Start assets S3 bucket (QSS3BucketName) is hosted. Required when using your own S3 bucket.
Type: String
QSS3KeyPrefix:
AllowedPattern: ^[0-9a-zA-Z-/]*$
ConstraintDescription: Quick Start key prefix can include numbers, lowercase letters, uppercase letters, hyphens (-), and forward slashes (/).
Default: quickstart-git2s3/
Description: Key prefix for the Quick Start assets S3 bucket. A key prefix is similar to a directory name that enables you to store similar data under the same directory in an S3 bucket. It can include numbers, lowercase letters, uppercase letters, hyphens (-), and forward slashes (/).
Type: String
VPCId:
Description: ID of the VPC in which the Lambda function runs.
Type: String
Default: ''
VPCCidrRange:
Description: CIDR range of the VPC.
Type: String
Default: ''
SubnetIds:
Description: SubnetIDs in which the Lambda function runs.
Type: CommaDelimitedList
Default: ''
ScmHostnameOverride:
Description: Name to override the hostname in the header of a webhook JSON payload.
Type: String
Default: ''
ExcludeGit:
Description: Choose False to omit the .git directory from the Git repository .zip file.
Type: String
Default: 'True'
AllowedValues: ['True', 'False']
Conditions:
UseAllowedIps: !Not
- !Equals
- !Ref 'AllowedIps'
- ''
UseApiSecret: !Not
- !Equals
- !Ref 'ApiSecret'
- ''
UseCustomDomain: !Not
- !Equals
- !Ref 'CustomDomainName'
- ''
AutoGenOutputBucketName: !Not
- !Equals
- !Ref 'OutputBucketName'
- ''
ShouldRunInVPC: !Not
- !Equals
- !Ref 'VPCId'
- ''
UsingDefaultBucket: !Equals [!Ref QSS3BucketName, 'aws-quickstart']
Resources:
LambdaZipsBucket:
Type: AWS::S3::Bucket
Properties:
Tags: []
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
SSEAlgorithm: AES256
PublicAccessBlockConfiguration:
BlockPublicAcls: true
BlockPublicPolicy: true
IgnorePublicAcls: true
RestrictPublicBuckets: true
VersioningConfiguration:
Status: Enabled
CopyZips:
Type: AWS::CloudFormation::CustomResource
Properties:
ServiceToken: !GetAtt 'CopyZipsFunction.Arn'
DestBucket: !Ref 'LambdaZipsBucket'
SourceBucket: !If [UsingDefaultBucket, !Sub '${QSS3BucketName}-${AWS::Region}', !Ref QSS3BucketName]
Prefix: !Ref 'QSS3KeyPrefix'
Objects:
- functions/packages/CreateSSHKey/lambda.zip
- functions/packages/DeleteBucketContents/lambda.zip
- functions/packages/GitPullS3/lambda.zip
CopyZipsRole:
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
Path: /
Policies:
- PolicyName: lambda-copier
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- s3:GetObject
Resource: !Sub
- arn:${AWS::Partition}:s3:::${S3Bucket}/${QSS3KeyPrefix}*
- S3Bucket: !If [UsingDefaultBucket, !Sub '${QSS3BucketName}-${AWS::Region}', !Ref QSS3BucketName]
- Effect: Allow
Action:
- s3:PutObject
- s3:DeleteObject
Resource:
- !Sub 'arn:${AWS::Partition}:s3:::${LambdaZipsBucket}/${QSS3KeyPrefix}*'
- Effect: Allow
Action:
- s3:*
Resource:
- '*'
CopyZipsFunction:
Type: AWS::Lambda::Function
Properties:
Description: Copies objects from a source S3 bucket to a destination.
Handler: index.handler
Runtime: python3.7
Role: !GetAtt 'CopyZipsRole.Arn'
Timeout: 240
Code:
ZipFile: !Join
- "\n"
- - import json
- import logging
- import threading
- import boto3
- import cfnresponse
- ''
- ''
- 'def copy_objects(source_bucket, dest_bucket, prefix, objects):'
- ' s3 = boto3.client(''s3'')'
- ' for o in objects:'
- ' key = prefix + o'
- ' copy_source = {'
- ' ''Bucket'': source_bucket,'
- ' ''Key'': key'
- ' }'
- ' s3.copy_object(CopySource=copy_source, Bucket=dest_bucket,
Key=key)'
- ''
- ''
- 'def delete_objects(bucket, prefix, objects):'
- ' s3 = boto3.client(''s3'')'
- ' objects = {''Objects'': [{''Key'': prefix + o} for o in objects]}'
- ' s3.delete_objects(Bucket=bucket, Delete=objects)'
- ''
- ''
- 'def timeout(event, context):'
- ' logging.error(''Execution is about to time out, sending failure
response to CloudFormation'')'
- ' cfnresponse.send(event, context, cfnresponse.FAILED, {}, None)'
- ''
- ''
- 'def handler(event, context):'
- ' # make sure we send a failure to CloudFormation if the function
is going to timeout'
- ' timer = threading.Timer((context.get_remaining_time_in_millis()
/ 1000.00) - 0.5, timeout, args=[event, context])'
- ' timer.start()'
- ''
- ' print(''Received event: %s'' % json.dumps(event))'
- ' status = cfnresponse.SUCCESS'
- ' try:'
- ' source_bucket = event[''ResourceProperties''][''SourceBucket'']'
- ' dest_bucket = event[''ResourceProperties''][''DestBucket'']'
- ' prefix = event[''ResourceProperties''][''Prefix'']'
- ' objects = event[''ResourceProperties''][''Objects'']'
- ' if event[''RequestType''] == ''Delete'':'
- ' delete_objects(dest_bucket, prefix, objects)'
- ' else:'
- ' copy_objects(source_bucket, dest_bucket, prefix, objects)'
- ' except Exception as e:'
- ' logging.error(''Exception: %s'' % e, exc_info=True)'
- ' status = cfnresponse.FAILED'
- ' finally:'
- ' timer.cancel()'
- ' cfnresponse.send(event, context, status, {}, None)'
- ''
KeyBucket:
Type: AWS::S3::Bucket
Properties:
Tags: []
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
SSEAlgorithm: AES256
PublicAccessBlockConfiguration:
BlockPublicAcls: true
BlockPublicPolicy: true
IgnorePublicAcls: true
RestrictPublicBuckets: true
VersioningConfiguration:
Status: Enabled
OutputBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !If
- AutoGenOutputBucketName
- !Ref 'OutputBucketName'
- !Ref 'AWS::NoValue'
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
SSEAlgorithm: AES256
PublicAccessBlockConfiguration:
BlockPublicAcls: true
BlockPublicPolicy: true
IgnorePublicAcls: true
RestrictPublicBuckets: true
VersioningConfiguration:
Status: Enabled
Tags: []
KMSKey:
Type: AWS::KMS::Key
Properties:
Description: AWS KWS key to encrypt and decrypt SSH keys stored in S3.
EnableKeyRotation: true
KeyPolicy:
Version: '2012-10-17'
Statement:
- Sid: Allow access for Key Administrators
Effect: Allow
Principal:
AWS:
- !Join
- ''
- - 'arn:aws:iam::'
- !Ref 'AWS::AccountId'
- :root
Action:
- kms:Create*
- kms:Describe*
- kms:Enable*
- kms:List*
- kms:Put*
- kms:Update*
- kms:Revoke*
- kms:Disable*
- kms:Get*
- kms:Delete*
- kms:ScheduleKeyDeletion
- kms:CancelKeyDeletion
Resource: '*'
- Sid: Allow use of the key
Effect: Allow
Principal:
AWS:
- !Join
- ''
- - 'arn:aws:iam::'
- !Ref 'AWS::AccountId'
- :root
Action:
- kms:Encrypt
- kms:Decrypt
- kms:ReEncrypt*
- kms:GenerateDataKey*
- kms:DescribeKey
Resource: '*'
- Sid: Allow attachment of persistent resources
Effect: Allow
Principal:
AWS:
- !Join
- ''
- - 'arn:aws:iam::'
- !Ref 'AWS::AccountId'
- :root
Action:
- kms:CreateGrant
- kms:ListGrants
- kms:RevokeGrant
Resource: '*'
Condition:
Bool:
kms:GrantIsForAWSResource: true
CreateSSHKeyRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
Path: /
Policies:
- PolicyName: git2cp-sshkeygen
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- s3:GetObject
Resource:
- !Join
- ''
- - 'arn:aws:s3:::'
- !Ref 'KeyBucket'
- /crypto.zip
- Effect: Allow
Action:
- s3:PutObject
Resource:
- !Join
- ''
- - 'arn:aws:s3:::'
- !Ref 'KeyBucket'
- /enc_key
- Effect: Allow
Action:
- kms:Encrypt
Resource:
- !GetAtt 'KMSKey.Arn'
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource:
- !Sub arn:${AWS::Partition}:logs:*:*:*
CreateSSHKeyLambda:
DependsOn: CopyZips
Type: AWS::Lambda::Function
Properties:
Handler: lambda_function.lambda_handler
MemorySize: 128
Role: !GetAtt 'CreateSSHKeyRole.Arn'
Runtime: python3.8
Timeout: 300
Code:
S3Bucket: !Ref 'LambdaZipsBucket'
S3Key: !Sub '${QSS3KeyPrefix}functions/packages/CreateSSHKey/lambda.zip'
CreateSSHKey:
Type: AWS::CloudFormation::CustomResource
Version: '1.0'
Properties:
ServiceToken: !GetAtt 'CreateSSHKeyLambda.Arn'
KeyBucket: !Ref 'KeyBucket'
Region: !Ref 'AWS::Region'
KMSKey: !Ref 'KMSKey'
DeleteBucketContentsRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
Path: /
Policies:
- PolicyName: git2cp-deletebucketcontents
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- s3:*
Resource:
- !Join
- ''
- - 'arn:aws:s3:::'
- !Ref 'KeyBucket'
- /*
- !Join
- ''
- - 'arn:aws:s3:::'
- !Ref 'OutputBucket'
- /*
- !Join
- ''
- - 'arn:aws:s3:::'
- !Ref 'KeyBucket'
- !Join
- ''
- - 'arn:aws:s3:::'
- !Ref 'OutputBucket'
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource:
- arn:aws:logs:*:*:*
DeleteBucketContentsLambda:
DependsOn: CopyZips
Type: AWS::Lambda::Function
Properties:
Handler: lambda_function.lambda_handler
MemorySize: 128
Role: !GetAtt 'DeleteBucketContentsRole.Arn'
Runtime: python3.8
Timeout: 300
Code:
S3Bucket: !Ref 'LambdaZipsBucket'
S3Key: !Sub '${QSS3KeyPrefix}functions/packages/DeleteBucketContents/lambda.zip'
DeleteBucketContents:
Type: AWS::CloudFormation::CustomResource
Version: '1.0'
DependsOn:
- KeyBucket
- OutputBucket
Properties:
ServiceToken: !GetAtt 'DeleteBucketContentsLambda.Arn'
KeyBucket: !Ref 'KeyBucket'
OutputBucket: !Ref 'OutputBucket'
CodeBuildServiceRole:
Type: "AWS::IAM::Role"
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: "Allow"
Principal:
Service: "codebuild.amazonaws.com"
Action:
- "sts:AssumeRole"
Path: "/"
ManagedPolicyArns:
- !Ref CodeBuildEndpointPolicy
Tags:
-
Key: 'tagging-policy'
Value: !Join ['-', ["test", "ok"]]
CodeBuildBasePolicy:
Type: 'AWS::IAM::ManagedPolicy'
Properties:
Description: Policy with base permissions for CodeBuild.
Path: /
Roles:
- !Ref CodeBuildServiceRole
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: "Allow"
Action:
- "logs:CreateLogGroup"
- "logs:PutLogEvents"
- "logs:CreateLogStream"
Resource:
- !Sub "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/codebuild/*"
- Effect: "Allow"
Action:
- "s3:GetObject"
- "s3:GetObjectVersion"
- "s3:GetBucketAcl"
- "s3:GetBucketLocation"
Resource:
- !GetAtt KeyBucket.Arn
- !Sub "${KeyBucket.Arn}/*"
- Effect: "Allow"
Action:
- "s3:PutObject"
Resource:
- !GetAtt OutputBucket.Arn
- !Sub "${OutputBucket.Arn}/*"
- Effect: "Allow"
Action:
- 'kms:Encrypt'
- 'kms:Decrypt'
- 'kms:ReEncrypt*'
- 'kms:GenerateDataKey*'
- 'kms:DescribeKey'
Resource:
- !GetAtt KMSKey.Arn
CodeBuildEndpointPolicy:
Type: 'AWS::IAM::ManagedPolicy'
Properties:
Description: Policy with permissions enabling CodeBuild to work with endpoints.
Path: /
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- 'ec2:CreateNetworkInterface'
- 'ec2:DescribeDhcpOptions'
- 'ec2:DescribeNetworkInterfaces'
- 'ec2:DeleteNetworkInterface'
- 'ec2:DescribeSubnets'
- 'ec2:DescribeSecurityGroups'
- 'ec2:DescribeVpcs'
Resource: '*'
- Effect: Allow
Action:
- 'ec2:CreateNetworkInterfacePermission'
Resource: !Sub 'arn:aws:ec2:${AWS::Region}:${AWS::AccountId}:network-interface/*'
GitPullRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
Path: /
Policies:
- PolicyName: git2cp-gitpull
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- kms:Decrypt
Resource:
- !GetAtt 'KMSKey.Arn'
- Effect: Allow
Action:
- s3:PutObject
Resource:
- !Join
- ''
- - 'arn:aws:s3:::'
- !Ref 'OutputBucket'
- !Join
- ''
- - 'arn:aws:s3:::'
- !Ref 'OutputBucket'
- /*
- Effect: Allow
Action:
- s3:GetObject
Resource:
- !Join
- ''
- - 'arn:aws:s3:::'
- !Ref 'KeyBucket'
- /enc_key
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource:
- arn:aws:logs:*:*:*
- Effect: Allow
Action:
- codebuild:StartBuild
- codebuild:BatchGetBuilds
Resource:
- !GetAtt GitPullCodeBuild.Arn
- Effect: Allow
Action:
- 'ec2:CreateNetworkInterface'
- 'ec2:DescribeDhcpOptions'
- 'ec2:DescribeNetworkInterfaces'
- 'ec2:DeleteNetworkInterface'
- 'ec2:DescribeSubnets'
- 'ec2:DescribeSecurityGroups'
- 'ec2:DescribeVpcs'
Resource:
- '*'
- Effect: Allow
Action:
- 'ec2:CreateNetworkInterfacePermission'
Resource: !Sub 'arn:aws:ec2:${AWS::Region}:${AWS::AccountId}:network-interface/*'
GitPullCodeBuild:
Type: AWS::CodeBuild::Project
Properties:
VpcConfig: !If
- ShouldRunInVPC
- SecurityGroupIds:
- !Ref 'GitPullSecurityGroup'
Subnets: !Ref 'SubnetIds'
VpcId: !Ref VPCId
- !Ref 'AWS::NoValue'
Artifacts:
Type: NO_ARTIFACTS
Environment:
Image: aws/codebuild/standard:2.0
Type: LINUX_CONTAINER
ComputeType: BUILD_GENERAL1_SMALL
QueuedTimeoutInMinutes: 60
ServiceRole: !GetAtt CodeBuildServiceRole.Arn
Source:
BuildSpec: |
version: 0.2
env:
exported-variables:
- GIT_COMMIT_ID
- GIT_COMMIT_MSG
phases:
install:
runtime-versions:
python: 3.7
# commands:
# - pip3 install boto3
build:
commands:
- echo "=======================Start-Deployment============================="
- echo "Getting the SSH Private Key"
- |
python3 - << "EOF"
from boto3 import client
import os
s3 = client('s3')
kms = client('kms')
enckey = s3.get_object(Bucket=os.getenv('KeyBucket'), Key=os.getenv('KeyObject'))['Body'].read()
privkey = kms.decrypt(CiphertextBlob=enckey)['Plaintext']
with open('enc_key.pem', 'w') as f:
print(privkey.decode("utf-8"), file=f)
EOF
- mv ./enc_key.pem ~/.ssh/id_rsa
- ls ~/.ssh/
- echo "Setting SSH config profile"
- |
cat > ~/.ssh/config <<EOF
Host *
AddKeysToAgent yes
StrictHostKeyChecking no
IdentityFile ~/.ssh/id_rsa
EOF
- chmod 600 ~/.ssh/id_rsa
- echo "Cloning the repository $GitUrl on branch $Branch"
- git clone --single-branch --depth=1 --branch $Branch $GitUrl .
- ls
- echo "Zipping the checked out contents"
- |
if [ "$exclude_git" = "True" ]; then
zip -r $outputbucketkey ./ -x '*.git*'
else
zip -r $outputbucketkey ./
fi
- ls -alh
- echo "Put the zipped Object to Output Bucket"
- aws s3 cp $outputbucketkey s3://$outputbucket/$outputbucketpath # --sse aws:kms --sse-kms-key-id $CodePipelineArtifactKMSKeyId
- export GIT_COMMIT_ID=$(git rev-parse --short HEAD)
- echo $GIT_COMMIT_ID
- export GIT_COMMIT_MSG="$(git log -1 --pretty=%B)"
- echo $GIT_COMMIT_MSG
- echo "=======================End-Deployment============================="
Type: NO_SOURCE
TimeoutInMinutes: 14
GitPullLambda:
DependsOn: CopyZips
Type: AWS::Lambda::Function
Properties:
Handler: lambda_function.lambda_handler
MemorySize: 128
Role: !GetAtt 'GitPullRole.Arn'
Runtime: python3.8
Timeout: 900
VpcConfig: !If
- ShouldRunInVPC
- SecurityGroupIds:
- !Ref 'GitPullSecurityGroup'
SubnetIds: !Ref 'SubnetIds'
- !Ref 'AWS::NoValue'
Environment:
Variables:
ExcludeGit: !Ref ExcludeGit
GitPullCodeBuild: !Ref 'GitPullCodeBuild'
Code:
S3Bucket: !Ref 'LambdaZipsBucket'
S3Key: !Sub '${QSS3KeyPrefix}functions/packages/GitPullS3/lambda.zip'
GitPullSecurityGroup:
Condition: ShouldRunInVPC
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Security Group to allow the Lambda function to access the Git service.
SecurityGroupEgress:
- CidrIp: 0.0.0.0/0
FromPort: 0
IpProtocol: tcp
ToPort: 65535
SecurityGroupIngress:
- CidrIp: !Ref 'VPCCidrRange'
FromPort: 0
IpProtocol: tcp
ToPort: 65535
VpcId: !Ref 'VPCId'
WebHookRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: apigateway.amazonaws.com
Action: sts:AssumeRole
Path: /
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AmazonAPIGatewayPushToCloudWatchLogs
Policies:
- PolicyName: git2cp-webhook
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- lambda:InvokeAsync
- lambda:InvokeFunction
Resource:
- !GetAtt 'GitPullLambda.Arn'
WebHookApi:
Type: AWS::ApiGateway::RestApi
Properties:
Body:
swagger: '2.0'
info:
version: '2016-07-26T07:34:38Z'
title: !Join
- ''
- - G2CP-
- !Ref 'AWS::StackName'
schemes:
- https
paths:
/gitpull:
post:
consumes:
- application/json
produces:
- application/json
responses:
'200':
description: 200 response
schema:
$ref: '#/definitions/Empty'
x-amazon-apigateway-integration:
type: aws
credentials: !GetAtt 'WebHookRole.Arn'
responses:
default:
statusCode: '200'
requestParameters:
integration.request.header.X-Amz-Invocation-Type: '''Event'''
passthroughBehavior: when_no_templates
httpMethod: POST
uri: !Join
- ''
- - 'arn:aws:apigateway:'
- !Ref 'AWS::Region'
- :lambda:path//2015-03-31/functions/
- !GetAtt 'GitPullLambda.Arn'
- /invocations
requestTemplates:
application/json: !Join
- ''
- - "#set($allParams = $input.params())\n"
- "{\n"
- "\"body-json\" : $input.json('$'),\n"
- "\"params\" : {\n"
- "#foreach($type in $allParams.keySet())\n"
- " #set($params = $allParams.get($type))\n"
- "\"$type\" : {\n"
- " #foreach($paramName in $params.keySet())\n"
- " \"$paramName\" : \"$util.escapeJavaScript($params.get($paramName))\"\
\n"
- " #if($foreach.hasNext),#end\n"
- " #end\n"
- "}\n"
- " #if($foreach.hasNext),#end\n"
- "#end\n"
- "},\n"
- "\"stage-variables\" : {\n"
- "#foreach($key in $stageVariables.keySet())\n"
- "\"$key\" : \"$util.escapeJavaScript($stageVariables.get($key))\"\
\n"
- " #if($foreach.hasNext),#end\n"
- "#end\n"
- "},\n"
- "\"context\" : {\n"
- " \"account-id\" : \"$context.identity.accountId\",\n"
- " \"api-id\" : \"$context.apiId\",\n"
- " \"api-key\" : \"$context.identity.apiKey\",\n"
- " \"authorizer-principal-id\" : \"$context.authorizer.principalId\"\
,\n"
- " \"caller\" : \"$context.identity.caller\",\n"
- " \"cognito-authentication-provider\" : \"$context.identity.cognitoAuthenticationProvider\"\
,\n"
- " \"cognito-authentication-type\" : \"$context.identity.cognitoAuthenticationType\"\
,\n"
- " \"cognito-identity-id\" : \"$context.identity.cognitoIdentityId\"\
,\n"
- " \"cognito-identity-pool-id\" : \"$context.identity.cognitoIdentityPoolId\"\
,\n"
- " \"http-method\" : \"$context.httpMethod\",\n"
- " \"stage\" : \"$context.stage\",\n"
- " \"source-ip\" : \"$context.identity.sourceIp\",\n"
- " \"user\" : \"$context.identity.user\",\n"
- " \"user-agent\" : \"$context.identity.userAgent\",\n"
- " \"user-arn\" : \"$context.identity.userArn\",\n"
- " \"request-id\" : \"$context.requestId\",\n"
- " \"resource-id\" : \"$context.resourceId\",\n"
- " \"resource-path\" : \"$context.resourcePath\",\n"
- " \"allowed-ips\" : \"$stageVariables.allowedips\",\n"
- " \"api-secrets\" : \"$stageVariables.apisecrets\",\n"
- ' "key-bucket" : "'
- !Ref 'KeyBucket'
- "\",\n"
- " \"output-bucket\" : \"$stageVariables.outputbucket\"\
,\n"
- ' "public-key" : "'
- !Ref 'CreateSSHKey'
- "\",\n"
- " \"raw-body\" : \"$util.escapeJavaScript($input.body).replace(\"\
\\'\",\"'\")\"\n"
- " }\n"
- '}'
securityDefinitions:
sigv4:
type: apiKey
name: Authorization
in: header
x-amazon-apigateway-authtype: awsSigv4
definitions:
Empty:
type: object
WebHookApiDeployment:
Type: AWS::ApiGateway::Deployment
Properties:
RestApiId: !Ref 'WebHookApi'
StageName: DummyStage
WebHookApiProdStage:
Type: AWS::ApiGateway::Stage
Properties:
DeploymentId: !Ref 'WebHookApiDeployment'
RestApiId: !Ref 'WebHookApi'
StageName: Prod
Variables:
outputbucket: !Ref 'OutputBucket'
allowedips: !If
- UseAllowedIps
- !Ref 'AllowedIps'
- !Ref 'AWS::NoValue'
apisecrets: !If
- UseApiSecret
- !Ref 'ApiSecret'
- !Ref 'AWS::NoValue'
CustomDomainCertificate:
Condition: UseCustomDomain
Type: AWS::CertificateManager::Certificate
Properties:
DomainName: !Ref 'CustomDomainName'
WebHookApiCustomDomainName:
Condition: UseCustomDomain
Type: AWS::ApiGateway::DomainName
Properties:
CertificateArn: !Ref 'CustomDomainCertificate'
DomainName: !Ref 'CustomDomainName'
WebHookApiCustomDomainNameMapping:
Condition: UseCustomDomain
Type: AWS::ApiGateway::BasePathMapping
Properties:
DomainName: !Ref 'CustomDomainName'
RestApiId: !Ref 'WebHookApi'
Outputs:
CustomDomainNameCNAME:
Value: !If
- UseCustomDomain
- !GetAtt 'WebHookApiCustomDomainName.DistributionDomainName'
- ''
PublicSSHKey:
Value: !Ref 'CreateSSHKey'
GitPullWebHookApi:
Value: !Join
- ''
- - ' https://'
- !If
- UseCustomDomain
- !Ref 'CustomDomainName'
- !Join
- ''
- - !Ref 'WebHookApi'
- .execute-api.
- !Ref 'AWS::Region'
- .amazonaws.com
- /
- !Ref 'WebHookApiProdStage'
- /gitpull
OutputBucketName:
Value: !Ref 'OutputBucket'