-
Notifications
You must be signed in to change notification settings - Fork 2
/
CodePipeline-Terraform-CF.yaml
468 lines (438 loc) · 15.2 KB
/
CodePipeline-Terraform-CF.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
AWSTemplateFormatVersion: "2010-09-09"
Description: CI/CD Pipeline for the Terraform projects
Parameters:
BuildImageName:
Type: String
Description: Docker image for application build
Default: aws/codebuild/amazonlinux2-x86_64-standard:3.0
PipelineBucket:
Type: String
Description: S3 Bucket to use with Pipeline
InitialSubscriberEmail:
Description: Initial email for the alerts
Type: String
Default: NONE
GitHubRepo:
Description: GitHub repo to watch as <Organization name>/<repository>
Type: String
GitHubBranch:
Description: Branch which this pipeline will monitor
Type: String
Default: main
CodeStarConnectionArn:
Description: pre-configured CodeStar Connection to the GitHub Org and Repo
Type: String
Environment:
Description: Environment label to use
Type: String
Default: dev
InfracostApiKey:
Description: API Key for Infracost
Type: String
AutoApproveDelaySeconds:
Description: Delay to trigger the auto-approve logic (in seconds)
Type: Number
Default: 30
AutoApproveDiffPercentThreshold:
Description: Relative difference in % between current and projected cloud spend, above which the manual approval will be needed
Type: Number
Default: 10
AutoApproveDiffAbsoluteThreshold:
Description: Absolute difference (in $) between current and projected cloud spend, above which the manual approval will be needed
Type: Number
Default: 100
Conditions:
ConditionSubscriptionEmailPresent:
!Not [ !Equals [ !Ref InitialSubscriberEmail, "NONE" ] ]
Resources:
PipelineNotificationsTopic:
Type: AWS::SNS::Topic
Properties:
DisplayName: !Sub ${AWS::StackName}-pipeline-notifications
Subscription:
- !If
- ConditionSubscriptionEmailPresent
- Endpoint: !Ref "InitialSubscriberEmail"
Protocol: email
- !Ref "AWS::NoValue"
PipelineServiceRole:
Type: AWS::IAM::Role
Properties:
RoleName: !Sub ${AWS::StackName}-pipeline-service-role
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action: sts:AssumeRole
Principal:
Service:
- codepipeline.amazonaws.com
- codebuild.amazonaws.com
Policies:
- PolicyName: root
PolicyDocument:
Version: "2012-10-17"
Statement:
- Sid: CodeStarConnection
Resource: !Ref CodeStarConnectionArn
Effect: Allow
Action:
- codestar-connections:UseConnection
- Sid: CodeBuildPermissions
Resource: "*"
Effect: Allow
Action:
- codebuild:StartBuild
- codebuild:BatchGetBuilds
- sns:Publish
- Sid: CloudWatchLogs
Resource: "*"
Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
- Sid: AccessPipelineBucket
Effect: Allow
Action:
- s3:Get*
- s3:ListBucket
Resource:
- !Sub arn:aws:s3:::${PipelineBucket}
- Sid: AccessPipelineBucketObjects
Effect: Allow
Action:
- s3:PutObject*
- s3:GetObject*
Resource:
- !Sub arn:aws:s3:::${PipelineBucket}/*
Pipeline:
Type: AWS::CodePipeline::Pipeline
Properties:
RoleArn: !GetAtt PipelineServiceRole.Arn
Name: !Sub ${AWS::StackName}
ArtifactStores:
- Region: !Ref AWS::Region
ArtifactStore:
Type: S3
Location: !Sub ${PipelineBucket}
Stages:
- Name: Source
Actions:
- Name: GitHub
RunOrder: 1
ActionTypeId:
Category: Source
Provider: CodeStarSourceConnection
Owner: AWS
Version: "1"
Namespace: GitHubSource
OutputArtifacts:
- Name: GitHubCode
Configuration:
ConnectionArn: !Ref CodeStarConnectionArn
FullRepositoryId: !Ref GitHubRepo
BranchName: !Ref GitHubBranch
OutputArtifactFormat: CODE_ZIP
DetectChanges: true
- Name: CreatePlan
Actions:
- Name: terraform-plan
RunOrder: 1
Namespace: TfPlan
InputArtifacts:
- Name: GitHubCode
OutputArtifacts:
- Name: TerraformPlan
ActionTypeId:
Category: Build
Provider: CodeBuild
Owner: AWS
Version: "1"
Configuration:
ProjectName: !Ref TerraformPlanProject
EnvironmentVariables: !Sub |
[
{"name": "EXECUTION_ID", "value": "#{codepipeline.PipelineExecutionId}"},
{"name": "BRANCH", "value": "#{GitHubSource.BranchName}"},
{"name": "REPO", "value": "#{GitHubSource.FullRepositoryName}"},
{"name": "COMMIT_ID", "value": "#{GitHubSource.CommitId}"},
{"name": "BUCKET", "value": "${PipelineBucket}"},
{"name": "TF_VAR_env", "value": "${Environment}"}
]
- Name: CheckCosts
Actions:
- Name: check-costs
RunOrder: 1
Namespace: CostsVariables
InputArtifacts:
- Name: GitHubCode
- Name: TerraformPlan
OutputArtifacts:
- Name: CostsReport
ActionTypeId:
Category: Build
Provider: CodeBuild
Owner: AWS
Version: "1"
Configuration:
ProjectName: !Ref CheckCostsProject
PrimarySource: GitHubCode
EnvironmentVariables: !Sub |
[
{"name": "EXECUTION_ID", "value": "#{codepipeline.PipelineExecutionId}"},
{"name": "env", "value": "${Environment}"},
{"name": "INFRACOST_API_KEY", "value": "${InfracostApiKey}"}
]
- Name: ReviewPlan
Actions:
- Name: review-plan
RunOrder: 1
ActionTypeId:
Category: Approval
Provider: Manual
Owner: AWS
Version: "1"
Configuration:
CustomData: "Please review the Terraform Plan. Costs: old $#{CostsVariables.PastTotalMonthlyCost}, new $#{CostsVariables.TotalMonthlyCost}, difference $#{CostsVariables.DiffTotalMonthlyCost}"
- Name: ApplyPlan
Actions:
- Name: terraform-apply
RunOrder: 1
InputArtifacts:
- Name: GitHubCode
- Name: TerraformPlan
ActionTypeId:
Category: Build
Provider: CodeBuild
Owner: AWS
Version: "1"
Configuration:
ProjectName: !Ref TerraformApplyProject
PrimarySource: GitHubCode
EnvironmentVariables: !Sub |
[
{"name": "EXECUTION_ID", "value": "#{codepipeline.PipelineExecutionId}"},
{"name": "BRANCH", "value": "#{GitHubSource.BranchName}"},
{"name": "REPO", "value": "#{GitHubSource.FullRepositoryName}"},
{"name": "COMMIT_ID", "value": "#{GitHubSource.CommitId}"},
{"name": "BUCKET", "value": "${PipelineBucket}"},
{"name": "TF_VAR_env", "value": "${Environment}"}
]
ProjectServiceRole:
Type: AWS::IAM::Role
Properties:
RoleName: !Sub ${AWS::StackName}-codebuild-role
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action: sts:AssumeRole
Principal:
Service:
- codebuild.amazonaws.com
# Used for Terraform, please restrict to minimal
ManagedPolicyArns:
- arn:aws:iam::aws:policy/AdministratorAccess
Policies:
- PolicyName: root
PolicyDocument:
Version: "2012-10-17"
Statement:
- Sid: CloudWatchLogs
Resource: "*"
Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
- Sid: AccessPipelineBucket
Effect: Allow
Action:
- s3:ListBucket
- s3:GetBucketVersioning
Resource:
- !Sub arn:aws:s3:::${PipelineBucket}
- Sid: AccessPipelineBucketObjects
Effect: Allow
Action:
- s3:PutObject
- s3:PutObjectAcl
- s3:GetObject
- s3:GetObjectVersion
Resource:
- !Sub arn:aws:s3:::${PipelineBucket}/*
- Sid: AccessApproveQueue
Effect: Allow
Action:
- sqs:SendMessage
- sqs:GetQueueUrl
Resource:
- !GetAtt AutoApproveQueue.Arn
TerraformPlanProject:
Type: AWS::CodeBuild::Project
Properties:
Name: !Sub ${AWS::StackName}-tf-plan
Artifacts:
Type: CODEPIPELINE
Source:
Type: CODEPIPELINE
BuildSpec: pipeline/buildspec-tf-plan.yaml
Environment:
ComputeType: BUILD_GENERAL1_SMALL
Type: LINUX_CONTAINER
Image: !Ref BuildImageName
ServiceRole: !GetAtt ProjectServiceRole.Arn
TerraformApplyProject:
Type: AWS::CodeBuild::Project
Properties:
Name: !Sub ${AWS::StackName}-tf-apply
Artifacts:
Type: CODEPIPELINE
Source:
Type: CODEPIPELINE
BuildSpec: pipeline/buildspec-tf-apply.yaml
Environment:
ComputeType: BUILD_GENERAL1_SMALL
Type: LINUX_CONTAINER
Image: !Ref BuildImageName
ServiceRole: !GetAtt ProjectServiceRole.Arn
CheckCostsProject:
Type: AWS::CodeBuild::Project
Properties:
Name: !Sub ${AWS::StackName}-check-costs
Artifacts:
Type: CODEPIPELINE
Source:
Type: CODEPIPELINE
BuildSpec: pipeline/buildspec-check-costs.yaml
Environment:
ComputeType: BUILD_GENERAL1_SMALL
Type: LINUX_CONTAINER
Image: !Ref BuildImageName
EnvironmentVariables:
- Name: SQS_QUEUE
Value: !Sub ${AutoApproveQueue}
ServiceRole: !GetAtt ProjectServiceRole.Arn
AutoApproveQueue:
Type: AWS::SQS::Queue
Properties:
QueueName: !Sub ${AWS::StackName}-autoapprove-queue
DelaySeconds: !Ref AutoApproveDelaySeconds
AutoApproveQueuePolicy:
Type: AWS::SQS::QueuePolicy
Properties:
Queues:
- Ref: AutoApproveQueue
PolicyDocument:
Id: AllowIncomingAccess
Statement:
- Action:
- sqs:SendMessage
- sqs:ReceiveMessage
Effect: "Allow"
Resource:
- !GetAtt AutoApproveQueue.Arn
Principal:
AWS:
- !Ref AWS::AccountId
AutoApproveLambdaFunction:
Type: "AWS::Lambda::Function"
Properties:
FunctionName: !Sub ${AWS::StackName}-autoapprove-function
Handler: index.lambda_handler
MemorySize: 128
Runtime: python3.11
Role: !GetAtt LambdaFunctionRole.Arn
Environment:
Variables:
SNSTopic: !Ref PipelineNotificationsTopic
DiffAbsolute: !Ref AutoApproveDiffAbsoluteThreshold
DiffPercent: !Ref AutoApproveDiffPercentThreshold
PipelineName: !Sub ${AWS::StackName}
Region: !Sub ${AWS::Region}
Code:
ZipFile: |
# Imports
import logging
# Set up the logger
logger = logging.getLogger()
logger.setLevel(logging.INFO)
#logger.setLevel(logging.DEBUG) # Very verbose
def lambda_handler(event, context):
logger.info("#EVENT")
logger.info(event)
LambdaFunctionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
Path: "/"
Policies:
- PolicyName: AppendToLogsPolicy
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource: "*"
- PolicyName: SQSQueueAccessPolicy
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- sqs:SendMessage
- sqs:ReceiveMessage
- sqs:ReceiveMessage
- sqs:DeleteMessage
- sqs:GetQueueAttributes
Resource:
- !GetAtt AutoApproveQueue.Arn
- PolicyName: PipelineAccessPolicy
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- codepipeline:EnableStageTransition
- codepipeline:GetPipeline
- codepipeline:GetPipelineState
- codepipeline:GetPipelineExecution
- codepipeline:ListPipelineExecutions
- codepipeline:ListActionExecutions
- codepipeline:ListActionTypes
- codepipeline:ListPipelines
- codepipeline:ListTagsForResource
- codepipeline:PutApprovalResult
Resource:
- !Sub arn:aws:codepipeline:${AWS::Region}:${AWS::AccountId}:${Pipeline}
- !Sub arn:aws:codepipeline:${AWS::Region}:${AWS::AccountId}:${Pipeline}/*
- PolicyName: SNSAccessPolicy
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- sns:Publish
Resource:
- !Ref PipelineNotificationsTopic
LambdaFunctionSqsEventSourceMapping:
Type: AWS::Lambda::EventSourceMapping
DependsOn:
- LambdaFunctionRole
Properties:
BatchSize: 1
Enabled: true
EventSourceArn: !GetAtt AutoApproveQueue.Arn
FunctionName: !GetAtt AutoApproveLambdaFunction.Arn