forked from thestackshack/serverless-api-cicd
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcloudformation.yml
More file actions
704 lines (681 loc) · 18.4 KB
/
Copy pathcloudformation.yml
File metadata and controls
704 lines (681 loc) · 18.4 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
AWSTemplateFormatVersion: '2010-09-09'
Parameters:
GitHubOwner:
Type: String
Description: GitHub repository owner
GitHubRepo:
Type: String
Default: aws-codepipeline-nested-stack
Description: GitHub repository name
GitHubToken:
Type: String
Description: GitHub repository OAuth token
ProjectName:
Type: String
Description: Project Name
ArtifactsBucket:
Type: String
Description: Artifacts bucket Name
Resources:
#
# CloudFormation IAM Role
#
CloudFormationRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- sts:AssumeRole
Principal:
Service:
- cloudformation.amazonaws.com
ManagedPolicyArns:
- arn:aws:iam::aws:policy/AdministratorAccess
#
# Role that our Lambda will assume to provide access to other AWS resources
#
IamRoleLambdaExecution:
Type: AWS::IAM::Role
DependsOn: CloudFormationRole
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
Path: '/'
#
# Create a Policy and attach it to our Lambda Role.
#
IamPolicyLambdaExecution:
Type: AWS::IAM::Policy
DependsOn: CloudFormationRole
Properties:
PolicyName: IamPolicyLambdaExecution
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
Resource: arn:aws:logs:us-east-1:*:*
- Effect: Allow
Action:
- logs:PutLogEvents
Resource: arn:aws:logs:us-east-1:*:*
- Effect: Allow
Action:
- codepipeline:PutJobSuccessResult
- codepipeline:PutJobFailureResult
Resource: '*'
- Effect: Allow
Action:
- s3:GetObject
- s3:GetObjectVersion
- s3:ListBucket
- s3:PutObject
Resource: '*'
- Effect: Allow
Action:
- lambda:UpdateFunctionCode
- lambda:UpdateAlias
- lambda:ListAliases
- lambda:ListVersionsByFunction
- lambda:DeleteFunction
Resource: '*'
Roles:
- Ref: IamRoleLambdaExecution
#
# Our Lambda function. Basic code has been added. You will replace the code later via your Github repo.
#
APIFunction:
Type: AWS::Lambda::Function
DependsOn: CloudFormationRole
Properties:
Handler: index.handler
Timeout: 5
Role:
Fn::GetAtt:
- IamRoleLambdaExecution
- Arn
Code:
S3Bucket: !Ref ArtifactsBucket
S3Key: 'index.js.zip'
Runtime: nodejs6.10
#
# Create two aliases for our Lambda function. DEV and PROD. These pointers may point to different versions of the
# function. This allows us to try out new code in our dev environment before promoting it to prod.
#
APIFunctionDevAlias:
Type: AWS::Lambda::Alias
DependsOn: CloudFormationRole
Properties:
FunctionName:
Ref: APIFunction
FunctionVersion: '$LATEST'
Name: DEV
APIFunctionProdAlias:
Type: AWS::Lambda::Alias
DependsOn: CloudFormationRole
Properties:
FunctionName:
Ref: APIFunction
FunctionVersion: '$LATEST'
Name: PROD
#
# We need to give API Gateway permission to invoke our Lambda function and aliases.
#
LambdaDevPermission:
Type: AWS::Lambda::Permission
DependsOn: CloudFormationRole
Properties:
Action: lambda:invokeFunction
FunctionName:
Ref: APIFunctionDevAlias
Principal: apigateway.amazonaws.com
SourceArn:
Fn::Join:
- ''
- - 'arn:aws:execute-api:'
- Ref: AWS::Region
- ':'
- Ref: AWS::AccountId
- ':'
- Ref: ApiGatewayRestApi
- '/*/*'
LambdaProdPermission:
Type: AWS::Lambda::Permission
DependsOn: CloudFormationRole
Properties:
Action: lambda:invokeFunction
FunctionName:
Ref: APIFunctionProdAlias
Principal: apigateway.amazonaws.com
SourceArn:
Fn::Join:
- ''
- - 'arn:aws:execute-api:'
- Ref: AWS::Region
- ':'
- Ref: AWS::AccountId
- ':'
- Ref: ApiGatewayRestApi
- '/*/*'
#
# Create the API Gateway
#
ApiGatewayRestApi:
Type: AWS::ApiGateway::RestApi
DependsOn: CloudFormationRole
Properties:
Name: ApiGatewayRestApi
ApiGatewayResource:
Type: AWS::ApiGateway::Resource
DependsOn: CloudFormationRole
Properties:
ParentId:
Fn::GetAtt:
- ApiGatewayRestApi
- RootResourceId
PathPart: api
RestApiId:
Ref: ApiGatewayRestApi
ApiGatewayResourceProxy:
Type: AWS::ApiGateway::Resource
DependsOn: CloudFormationRole
Properties:
ParentId:
Ref: ApiGatewayResource
PathPart: '{proxy+}'
RestApiId:
Ref: ApiGatewayRestApi
#
# Create a role that gives API Gateway permission to write to CloudWatch Logs.
#
ApiGatewayCloudWatchLogsRole:
Type: AWS::IAM::Role
DependsOn: CloudFormationRole
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- apigateway.amazonaws.com
Action:
- sts:AssumeRole
Policies:
- PolicyName: ApiGatewayLogsPolicy
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:DescribeLogGroups
- logs:DescribeLogStreams
- logs:PutLogEvents
- logs:GetLogEvents
- logs:FilterLogEvents
Resource: "*"
#
# Attach the role to API Gateway
#
ApiGatewayAccount:
Type: AWS::ApiGateway::Account
DependsOn: CloudFormationRole
Properties:
CloudWatchRoleArn:
Fn::GetAtt:
- ApiGatewayCloudWatchLogsRole
- Arn
#
# Create an API Gateway stage that invokes either the DEV or PROD Lambda alias. This allows us to have different
# api endpoints, one for dev and one for prod.
#
ApiGatewayStageDEV:
DependsOn:
- ApiGatewayAccount
- CloudFormationRole
Type: AWS::ApiGateway::Stage
Properties:
DeploymentId:
Ref: ApiGatewayDeployment
MethodSettings:
- DataTraceEnabled: true
HttpMethod: "*"
LoggingLevel: INFO
ResourcePath: "/*"
RestApiId:
Ref: ApiGatewayRestApi
StageName: dev
Variables:
LambdaAlias: DEV
ApiGatewayStagePROD:
DependsOn:
- ApiGatewayAccount
- CloudFormationRole
Type: AWS::ApiGateway::Stage
Properties:
DeploymentId:
Ref: ApiGatewayDeployment
MethodSettings:
- DataTraceEnabled: true
HttpMethod: "*"
LoggingLevel: INFO
ResourcePath: "/*"
RestApiId:
Ref: ApiGatewayRestApi
StageName: prod
Variables:
LambdaAlias: PROD
#
# Create a GET and POST method that each invoke our Lambda
#
ApiGatewayMethod:
Type: AWS::ApiGateway::Method
DependsOn: CloudFormationRole
Properties:
HttpMethod: ANY
RequestParameters: {}
ResourceId:
Ref: ApiGatewayResource
RestApiId:
Ref: ApiGatewayRestApi
AuthorizationType: NONE
Integration:
IntegrationHttpMethod: POST
Type: AWS_PROXY
Uri:
Fn::Join:
- ''
- - 'arn:aws:apigateway:'
- Ref: AWS::Region
- ':lambda:path/2015-03-31/functions/'
- Fn::GetAtt:
- APIFunction
- Arn
- ':${stageVariables.LambdaAlias}'
- '/invocations'
MethodResponses: []
ApiGatewayMethoProxy:
Type: AWS::ApiGateway::Method
DependsOn: CloudFormationRole
Properties:
HttpMethod: ANY
RequestParameters: {}
ResourceId:
Ref: ApiGatewayResourceProxy
RestApiId:
Ref: ApiGatewayRestApi
AuthorizationType: NONE
Integration:
IntegrationHttpMethod: POST
Type: AWS_PROXY
Uri:
Fn::Join:
- ''
- - 'arn:aws:apigateway:'
- Ref: AWS::Region
- ':lambda:path/2015-03-31/functions/'
- Fn::GetAtt:
- APIFunction
- Arn
- ':${stageVariables.LambdaAlias}'
- '/invocations'
MethodResponses: []
ApiGatewayMethodOptions:
Type: AWS::ApiGateway::Method
Properties:
AuthorizationType: NONE
ResourceId:
Ref: ApiGatewayResourceProxy
RestApiId:
Ref: ApiGatewayRestApi
HttpMethod: OPTIONS
Integration:
IntegrationResponses:
- StatusCode: 200
ResponseParameters:
method.response.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'"
method.response.header.Access-Control-Allow-Methods: "'POST,OPTIONS'"
method.response.header.Access-Control-Allow-Origin: "'*'"
ResponseTemplates:
application/json: ''
PassthroughBehavior: WHEN_NO_MATCH
RequestTemplates:
application/json: '{"statusCode": 200}'
Type: MOCK
MethodResponses:
- StatusCode: 200
ResponseModels:
application/json: 'Empty'
ResponseParameters:
method.response.header.Access-Control-Allow-Headers: false
method.response.header.Access-Control-Allow-Methods: false
method.response.header.Access-Control-Allow-Origin: false
#
# Create the API Gateway deployment which uses both the GET and POST methods
#
ApiGatewayDeployment:
Type: AWS::ApiGateway::Deployment
DependsOn: CloudFormationRole
Properties:
RestApiId:
Ref: ApiGatewayRestApi
StageName: DummyStage
DependsOn:
- ApiGatewayMethod
- ApiGatewayMethoProxy
#
# CI/CD CodePipeline
#
#
# Code Build IAM Role
#
CodeBuildRole:
Type: AWS::IAM::Role
DependsOn: CloudFormationRole
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- sts:AssumeRole
Principal:
Service:
- codebuild.amazonaws.com
Policies:
- PolicyName: ServiceRole
PolicyDocument:
Version: 2012-10-17
Statement:
- Sid: CloudWatchWriteLogsPolicy
Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource: '*'
- Sid: S3GetObjectPolicy
Effect: Allow
Action:
- s3:GetObject
- s3:GetObjectVersion
Resource: '*'
- Sid: S3PutObjectPolicy
Effect: Allow
Action:
- s3:PutObject
Resource: '*'
#
# Code Pipeline IAM Role
#
CodePipelineRole:
Type: AWS::IAM::Role
DependsOn: CloudFormationRole
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- sts:AssumeRole
Principal:
Service:
- codepipeline.amazonaws.com
ManagedPolicyArns:
- arn:aws:iam::aws:policy/AdministratorAccess
#
# Code Build project
#
CodeBuildProject:
Type: AWS::CodeBuild::Project
DependsOn: CloudFormationRole
Properties:
Artifacts:
Type: CODEPIPELINE
Environment:
ComputeType: BUILD_GENERAL1_SMALL
Image: aws/codebuild/eb-nodejs-6.10.0-amazonlinux-64:4.0.0
Type: LINUX_CONTAINER
Name:
Fn::Join:
- ''
- - Ref: ProjectName
- '-code-build'
ServiceRole: !GetAtt CodeBuildRole.Arn
Source:
Type: CODEPIPELINE
BuildSpec: api/buildspec.yml
TimeoutInMinutes: 5 # must be between 5 minutes and 8 hours
#
# Package Lambda function. Last step in the CodePipeline
#
PackageFunction:
Type: AWS::Lambda::Function
DependsOn: CloudFormationRole
Properties:
Handler: package.handler
Timeout: 5
Role:
Fn::GetAtt:
- IamRoleLambdaExecution
- Arn
Code:
S3Bucket: !Ref ArtifactsBucket
S3Key: 'package.js.zip'
Runtime: nodejs6.10
#
# Package Lambda function. Last step in the CodePipeline
#
DeployFunction:
Type: AWS::Lambda::Function
DependsOn: CloudFormationRole
Properties:
Handler: deploy.deploy
Timeout: 5
Role:
Fn::GetAtt:
- IamRoleLambdaExecution
- Arn
Code:
S3Bucket: !Ref ArtifactsBucket
S3Key: 'deploy.js.zip'
Runtime: nodejs6.10
ShowFunction:
Type: AWS::Lambda::Function
DependsOn: CloudFormationRole
Properties:
Handler: deploy.show
Timeout: 5
Role:
Fn::GetAtt:
- IamRoleLambdaExecution
- Arn
Code:
S3Bucket: !Ref ArtifactsBucket
S3Key: 'deploy.js.zip'
Runtime: nodejs6.10
#
# Code Pipeline 'master'
#
CodePipelineMaster:
Type: AWS::CodePipeline::Pipeline
DependsOn: CloudFormationRole
Properties:
ArtifactStore:
Type: S3
Location: !Ref ArtifactsBucket
RestartExecutionOnUpdate: true
RoleArn: !GetAtt CodePipelineRole.Arn
Stages:
- Name: Source
Actions:
- Name: Source
ActionTypeId:
Category: Source
Owner: ThirdParty
Version: 1
Provider: GitHub
Configuration:
Owner: !Ref GitHubOwner
Repo: !Ref GitHubRepo
Branch: 'master'
OAuthToken: !Ref GitHubToken
OutputArtifacts:
- Name: SourceOutput
RunOrder: 1
- Name: StackDeploy
Actions:
- Name: CreateUpdateStack
ActionTypeId:
Category: Deploy
Owner: AWS
Provider: CloudFormation
Version: 1
Configuration:
ActionMode: CREATE_UPDATE
Capabilities: CAPABILITY_IAM
RoleArn: !GetAtt CloudFormationRole.Arn
StackName: !Ref AWS::StackName
TemplatePath: SourceOutput::infrastructure/cloudformation.yml
ParameterOverrides: !Sub |
{
"GitHubOwner": "${GitHubOwner}",
"GitHubRepo": "${GitHubRepo}",
"GitHubToken": "${GitHubToken}",
"ArtifactsBucket": "${ArtifactsBucket}",
"ProjectName": "${ProjectName}"
}
InputArtifacts:
- Name: SourceOutput
- Name: Build
Actions:
- Name: BuildAndTest
ActionTypeId:
Category: Build
Owner: AWS
Provider: CodeBuild
Version: 1
Configuration:
ProjectName: !Ref CodeBuildProject
InputArtifacts:
- Name: SourceOutput
OutputArtifacts:
- Name: BuildOutput
- Name: Package
Actions:
- Name: Package
ActionTypeId:
Category: Invoke
Owner: AWS
Provider: Lambda
Version: 1
InputArtifacts:
- Name: BuildOutput
- Name: SourceOutput
Configuration:
FunctionName: !Ref PackageFunction
UserParameters: 'master'
#
# Code Pipeline 'develop'
#
CodePipelineDevelop:
Type: AWS::CodePipeline::Pipeline
DependsOn: CloudFormationRole
Properties:
ArtifactStore:
Type: S3
Location: !Ref ArtifactsBucket
RestartExecutionOnUpdate: true
RoleArn: !GetAtt CodePipelineRole.Arn
Stages:
- Name: Source
Actions:
- Name: Source
ActionTypeId:
Category: Source
Owner: ThirdParty
Version: 1
Provider: GitHub
Configuration:
Owner: !Ref GitHubOwner
Repo: !Ref GitHubRepo
Branch: 'develop'
OAuthToken: !Ref GitHubToken
OutputArtifacts:
- Name: SourceOutput
RunOrder: 1
- Name: Build
Actions:
- Name: BuildAndTest
ActionTypeId:
Category: Build
Owner: AWS
Provider: CodeBuild
Version: 1
Configuration:
ProjectName: !Ref CodeBuildProject
InputArtifacts:
- Name: SourceOutput
OutputArtifacts:
- Name: BuildOutput
- Name: Package
Actions:
- Name: Package
ActionTypeId:
Category: Invoke
Owner: AWS
Provider: Lambda
Version: 1
InputArtifacts:
- Name: BuildOutput
- Name: SourceOutput
Configuration:
FunctionName: !Ref PackageFunction
UserParameters: 'develop'
#
# Return the API Gateway endpoints.
#
Outputs:
ServiceEndpointProd:
Description: URL of the PROD service endpoint
Value:
Fn::Join:
- ''
- - 'https://'
- Ref: ApiGatewayRestApi
- '.execute-api.'
- Ref: AWS::Region
- '.amazonaws.com/prod/api'
ServiceEndpointDev:
Description: URL of the DEV service endpoint
Value:
Fn::Join:
- ''
- - 'https://'
- Ref: ApiGatewayRestApi
- '.execute-api.'
- Ref: AWS::Region
- '.amazonaws.com/dev/api'
DeployFunction:
Description: Deploy Lambda Function
Value: !Ref DeployFunction
ShowFunction:
Description: Show Lambda Function
Value: !Ref ShowFunction
APIFunction:
Description: API Lambda Function
Value: !Ref APIFunction