-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpipeline.yaml
565 lines (528 loc) · 18.7 KB
/
pipeline.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
AWSTemplateFormatVersion: 2010-09-09
Description: CodePipeline uses CodeBuild and GitHub
Parameters:
GitHubOwner:
Type: String
Description: Name of the GitHub repository owner, for example, your company's GitHub name. This is not the repo name.
GitHubRepoName:
Type: String
Description: Name of the GitHub Repo that this pipeline should interact with
GitHubBranchName:
Type: String
Description: Name of the GitHub branch that should trigger the pipeline
GitHubConnectionArn:
Type: String
Description: ARN for the GitHub Connection v2 set up in the account in CodePipeline
PipelineArtifactsBucketName:
Type: String
Description: Create a name for a bucket that will store the pipeline artifacts (this bucket is created with this template)
Default: demo-pipeline-artifacts
ProductName:
Type: String
DeployRegion:
Type: String
Default: us-west-2
Environment:
Type: String
TargetAccountForCFnDeployment:
Type: String
Description: >
This pipeline deploys a CloudFormation template into an AWS Account. It is currently not set up for cross-account deployment.
This parameter should be the account number that the CloudFormation template should be deployed into.
PipelineName:
Type: String
Description: >
Create a descriptive and friendly name for the pipeline. Do not include the environment (such as dev),
as this will be added to the name automatically.
Resources:
#------- CodeBuild -------
DemoCodeBuildProject:
Type: AWS::CodeBuild::Project
Properties:
Artifacts:
Type: CODEPIPELINE
Description: Does something
EncryptionKey: !GetAtt CMKKeyForPipeline.Arn
Environment:
Type: LINUX_CONTAINER
ComputeType: BUILD_GENERAL1_SMALL
Image: aws/codebuild/standard:2.0
EnvironmentVariables:
- Name: ROLE
Value: ""
- Name: DEPLOY_REGION
Value: ""
LogsConfig:
CloudWatchLogs:
Status: "ENABLED"
Name: !Sub DemoBuildProject-${Environment}
ServiceRole: !GetAtt DemoPipelineCodeBuildRole.Arn
TimeoutInMinutes: 10
Source:
Type: CODEPIPELINE
BuildSpec: |
version: 0.2
phases:
install:
runtime-versions:
python: 3.7
build:
commands:
- echo "Checking current working directory"
- ls
CodeBuildCfnNagScan:
Type: AWS::CodeBuild::Project
Properties:
Name: !Sub CodeBuild-CfnNag-Scan-${Environment}
Description: Independent CfnNag scan project for post build artifacts
Artifacts:
Type: CODEPIPELINE
EncryptionKey: !GetAtt CMKKeyForPipeline.Arn
Environment:
Type: LINUX_CONTAINER
ComputeType: BUILD_GENERAL1_SMALL
Image: aws/codebuild/standard:2.0
LogsConfig:
CloudWatchLogs:
Status: "ENABLED"
ServiceRole: !GetAtt DemoPipelineCodeBuildRole.Arn
TimeoutInMinutes: 10
Source:
Type: CODEPIPELINE # specifies the source code settings for the project, such as the source code's repository type and location - source code placed in S3 bucket.
BuildSpec: |
version: 0.2
phases:
install:
runtime-versions:
ruby: 2.6
commands:
- echo "Installing cfn_nag utility - `pwd`"
- gem install cfn-nag
- cfn_nag -v
- echo "cfn_nag utility installation complete `date`"
build:
commands:
- echo "Starting cfn_nag scanning `date` in `pwd`"
- for y in `find deployment/dist/* -name "*.template"`; do echo "============= $y ================" ; cfn_nag --fail-on-warnings $y || ec1=$?; done
- if [ "$ec1" -ne "0" ]; then echo 'ERROR-1'; else echo 'SUCCESS-1'; ec1=0; fi
- echo "Exit Code 1 `echo $ec1`"
- for y in `find deployment/global-s3-assets/* -name "*.template"`; do echo "============= $y ================" ; cfn_nag --fail-on-warnings $y || ec2=$?; done
- if [ "$ec2" -ne "0" ]; then echo 'ERROR-2'; else echo 'SUCCESS-2'; ec2=0; fi
- echo "Exit Code 2 `echo $ec2`"
- echo "Completed cfn_nag scanning `date`"
- echo "Analyze exit codes and exit"
- if [ "$ec1" -ne "0" ] || [ "$ec2" -ne "0" ]; then echo 'ERROR'; ec=1; else echo 'SUCCESS'; ec=0; fi;
- echo "Exit Code Final `echo $ec`"
- exit $ec
artifacts:
files:
- '**/*'
CodeBuildDeployCFnS3Bucket:
Type: AWS::CodeBuild::Project
Properties:
Name: !Sub DeployCloudFormationTemplate-${Environment}
Description: Deploys an S3 bucket with CloudFormation stack
ServiceRole: !GetAtt DemoPipelineCodeBuildRole.Arn
TimeoutInMinutes: 60
Artifacts:
Type: CODEPIPELINE
Environment:
Type: LINUX_CONTAINER
ComputeType: BUILD_GENERAL1_SMALL
Image: aws/codebuild/docker:18.09.0
PrivilegedMode: true
EnvironmentVariables:
- Name: ROLE
Value: ""
- Name: DEPLOY_REGION
Value: ""
- Name: TEMPLATE_FILE
Value: ""
- Name: PARAMETER_FILE
Value: ""
- Name: STACKPREFIX
Value: ""
LogsConfig:
CloudWatchLogs:
Status: ENABLED
GroupName: !Ref DeployCodePipelineCloudformationLogGroup
Source:
Type: CODEPIPELINE
BuildSpec: !Sub |
version: 0.2
phases:
install:
commands:
- sudo apt-get update
- sudo apt-get -y install unzip jq
pre_build:
commands:
- PRODUCTNAME=${ProductName}
- STACKNAME=$STACKPREFIX$PRODUCTNAME
- printenv
- ls -lha
- cat "./s3-bucket.yaml"
- cp $TEMPLATE_FILE template.yaml
- cp $PARAMETER_FILE parameters.json
build:
commands:
- DEPLOY_CREDENTIALS=$(aws sts assume-role --role-arn $ROLE --role-session-name codebuild-session)
- export AWS_ACCESS_KEY_ID=$(echo $DEPLOY_CREDENTIALS | jq .Credentials.AccessKeyId | xargs)
- export AWS_SECRET_ACCESS_KEY=$(echo $DEPLOY_CREDENTIALS | jq .Credentials.SecretAccessKey | xargs)
- export AWS_SESSION_TOKEN=$(echo $DEPLOY_CREDENTIALS | jq .Credentials.SessionToken | xargs)
- aws cloudformation describe-stacks --region $DEPLOY_REGION --stack-name $STACKNAME > describe_stack.log || true
- |
if [ -s describe_stack.log ] && [ "$(jq -r .Stacks[0].StackStatus describe_stack.log)" = "ROLLBACK_COMPLETE" ]; then
echo "Old stack is in \"ROLLBACK_COMPLETE\" state. Deleting old stack"
aws cloudformation delete-stack --stack-name $STACKNAME --region $DEPLOY_REGION
aws cloudformation wait stack-delete-complete --stack-name $STACKNAME --region $DEPLOY_REGION
fi
- TIMESTAMP=$(date -u "+%Y-%m-%dT%H:%M:%S")
- >
aws cloudformation deploy --template-file template.yaml \
--capabilities CAPABILITY_NAMED_IAM \
--role-arn $ROLE \
--stack-name $STACKNAME \
--region $DEPLOY_REGION \
--no-fail-on-empty-changeset \
--parameter-overrides file://parameters.json ||
(aws cloudformation describe-stack-events \
--stack-name $STACKNAME \
--output table \
--region $DEPLOY_REGION \
--query "StackEvents[?Timestamp >= \`$TIMESTAMP\`].[Timestamp,ResourceType,LogicalResourceId,ResourceStatus,ResourceStatusReason]" && false)
post_build:
commands:
- aws cloudformation describe-stacks --stack-name $STACKNAME --query 'Stacks[*].Outputs' | jq '.[]' > ./cloudformation-outputs.json
- cat "./cloudformation-outputs.json"
artifacts:
files:
- '**/*'
CodeBuildTestDeployment:
Type: AWS::CodeBuild::Project
Properties:
Artifacts:
Type: CODEPIPELINE
Name: !Sub CodeBuildTestDeploy-${Environment}
Description: Runs tests after deployment of CloudFormation
EncryptionKey: !GetAtt CMKKeyForPipeline.Arn
Environment:
Type: LINUX_CONTAINER
ComputeType: BUILD_GENERAL1_SMALL
Image: aws/codebuild/standard:2.0
EnvironmentVariables:
- Name: ROLE
Value: ""
- Name: DEPLOY_REGION
Value: ""
LogsConfig:
CloudWatchLogs:
Status: "ENABLED"
ServiceRole: !GetAtt DemoPipelineCodeBuildRole.Arn
TimeoutInMinutes: 10
Source:
Type: CODEPIPELINE
BuildSpec: |
version: 0.2
phases:
install:
runtime-versions:
python: 3.7
build:
commands:
- echo "Checking current working directory"
- ls
- echo "Running tests"
- cat "./cloudformation-outputs.json"
- echo "Tests passed"
#------- CodePipeline -------
DemoPipeline:
Type: AWS::CodePipeline::Pipeline
Properties:
ArtifactStore:
Type: S3
EncryptionKey:
Id: !GetAtt CMKKeyForPipeline.Arn
Type: KMS
Location: !Ref CodePipelineS3Bucket
RoleArn: !GetAtt DemoPipelineRole.Arn
Name: !Sub ${PipelineName}-${Environment}
Stages:
- Name: GitHubSource
Actions:
- Name: SourceCodeStar
ActionTypeId:
Category: Source
Owner: AWS
Version: "1"
Provider: CodeStarSourceConnection
Configuration:
ConnectionArn: !Ref GitHubConnectionArn
FullRepositoryId: !Sub "${GitHubOwner}/${GitHubRepoName}"
BranchName: !Ref GitHubBranchName
OutputArtifacts:
- Name: SourceOutput
RunOrder: 1
- Name: DirectoryList
Actions:
- Name: DirectoryList
ActionTypeId:
Category: Build
Owner: AWS
Version: '1'
Provider: CodeBuild
Configuration:
ProjectName: !Ref DemoCodeBuildProject
RunOrder: 1
InputArtifacts:
- Name: SourceOutput
- Name: CfnNagScan
Actions:
- Name: CfnNagScan
ActionTypeId:
Category: Build
Owner: AWS
Version: '1'
Provider: CodeBuild
Configuration:
ProjectName: !Ref CodeBuildCfnNagScan
RunOrder: 1
InputArtifacts:
- Name: SourceOutput
OutputArtifacts:
- Name: CfnNagScanArtifact
- Name: ManualApproval
Actions:
- Name: ManualApproval
ActionTypeId:
Category: Approval
Owner: AWS
Provider: Manual
Version: "1"
Configuration:
CustomData: "Approval will lead to the deployment of a CloudFormation Stack"
RunOrder: 1
- Name: DeployCloudFormationToDev
Actions:
- Name: DeployCloudFormation
ActionTypeId:
Category: Build
Owner: AWS
Version: "1"
Provider: CodeBuild
Configuration:
ProjectName: !Ref CodeBuildDeployCFnS3Bucket
EnvironmentVariables: !Sub | # Uses DeploymentRole, which is created with a cloudformation template called "deployment-role.yaml"
[
{
"name": "ROLE",
"value": "arn:aws:iam::${TargetAccountForCFnDeployment}:role/DeploymentRole"
},
{
"name": "DEPLOY_REGION",
"value": "${DeployRegion}"
},
{
"name": "TEMPLATE_FILE",
"value": "./s3-bucket.yaml"
},
{
"name": "PARAMETER_FILE",
"value": "./parameters/dev.json"
},
{
"name": "STACKPREFIX",
"value": "${Environment}-"
}
]
RunOrder: 1
InputArtifacts:
- Name: SourceOutput
OutputArtifacts:
- Name: CFnOutput
- Name: TestDeployment
Actions:
- Name: TestDeployment
ActionTypeId:
Category: Build
Owner: AWS
Version: '1'
Provider: CodeBuild
Configuration:
ProjectName: !Ref CodeBuildTestDeployment
RunOrder: 1
InputArtifacts:
- Name: CFnOutput
#------- LogGroup -------
DeployCodePipelineCloudformationLogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub CodeBuildDeployCloudformationDemoLogGroup--${Environment}
RetentionInDays: 30
#------- Encryption -------
CMKKeyForPipeline:
Type: AWS::KMS::Key
Properties:
Description: "CMK to encrypt Pipeline"
KeyPolicy:
Version: "2012-10-17"
Id: "key-default-1"
Statement:
- Sid: "Enable IAM User Permissions"
Effect: "Allow"
Principal:
AWS: !Sub "arn:aws:iam::${AWS::AccountId}:root"
Action: "kms:*"
Resource: "*" # refers to this CMK
- Sid: "Allow use of the key"
Effect: "Allow"
Principal: "*"
Action:
- "kms:DescribeKey"
- "kms:Encrypt"
- "kms:Decrypt"
- "kms:ReEncrypt*"
- "kms:GenerateDataKey"
- "kms:GenerateDataKeyWithoutPlaintext"
- "kms:CreateGrant"
Resource: "*"
CMKAlias:
Type: AWS::KMS::Alias
Properties:
AliasName: !Sub alias/DemoPipelineCMK/${Environment}
TargetKeyId:
Ref: CMKKeyForPipeline
#------- Encrypted Bucket for Pipeline Artifacts-------
CodePipelineS3Bucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !Sub ${PipelineArtifactsBucketName}-${Environment}
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
SSEAlgorithm: aws:kms
KMSMasterKeyID: !Ref CMKKeyForPipeline
S3BucketPolicy:
Type: AWS::S3::BucketPolicy
Properties:
Bucket: !Ref CodePipelineS3Bucket
PolicyDocument:
Statement:
- Sid: DenyUnEncryptedObjectUploads
Effect: Deny
Principal: "*"
Action:
- s3:PutObject
Resource:
- !Sub arn:aws:s3:::${PipelineArtifactsBucketName}-${Environment}/*
Condition:
StringNotEquals:
s3:x-amz-server-side-encryption: aws:kms
- Sid: DenyInsecureConnections
Effect: Deny
Principal: "*"
Action: "s3:*"
Resource:
- !Sub arn:aws:s3:::${PipelineArtifactsBucketName}-${Environment}/*
Condition:
Bool:
aws:SecureTransport: false
#------- IAM Permissions -------
DemoPipelineCodeBuildRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- codebuild.amazonaws.com
Action:
- sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/AmazonEC2FullAccess
Path: /
DemoPipelineCodeBuildPolicy:
Type: AWS::IAM::ManagedPolicy
Properties:
ManagedPolicyName: !Sub DemoCodeBuildPipelinePolicy-${Environment}
Roles:
- !Ref DemoPipelineCodeBuildRole
PolicyDocument:
Version: "2012-10-17"
Statement:
- Sid: CloudWatchLogsPolicy
Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource: "*"
- Sid: S3Policy
Effect: Allow
Action:
- s3:GetObject
- s3:GetObjectVersion
- s3:PutObject
- s3:GetBucketAcl
- s3:GetBucketLocation
Resource: "*"
- Sid: RolePermissions
Effect: Allow
Action:
- iam:PassRole
- iam:ListInstanceProfiles
Resource:
- "*"
- Sid: AssumeRolePermissions
Effect: Allow
Action:
- sts:AssumeRole
Resource:
- "arn:aws:iam::*:role/DeploymentRole"
- Effect: Allow
Action:
- kms:Encrypt,
- kms:Decrypt,
- kms:ReEncrypt*,
- kms:GenerateDataKey*,
- kms:DescribeKey,
- kms:CreateGrant
Resource: "*"
DemoPipelineRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- codepipeline.amazonaws.com
Action:
- sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/AWSCodePipelineFullAccess
- arn:aws:iam::aws:policy/AmazonS3FullAccess
- arn:aws:iam::aws:policy/AWSCodeDeployFullAccess
- arn:aws:iam::aws:policy/AWSCodeBuildAdminAccess
Path: /
DemoPipelinePolicy:
Type: AWS::IAM::Policy
Properties:
PolicyName: !Sub DemoPipelinePolicy-${AWS::Region}
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- iam:ListRoles
- iam:PassRole
- cloudformation:*
- codebuild:BatchGetBuilds
- codebuild:StartBuild
Resource:
- "*"
Roles:
- !Ref DemoPipelineRole