-
Notifications
You must be signed in to change notification settings - Fork 256
/
Copy pathsra-common-cfct-setup-main.yaml
541 lines (515 loc) · 21.4 KB
/
sra-common-cfct-setup-main.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
########################################################################
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
########################################################################
AWSTemplateFormatVersion: 2010-09-09
Description:
This template deploys Customizations for Control Tower (CFCT). - 'common_cfct_setup' solution in the repo,
https://github.com/aws-samples/aws-security-reference-architecture-examples (sra-1ssgnse2a)
Metadata:
SRA:
Version: 1.2
Entry: Parameters for deploying CFCT solution without resolving SSM parameters
Order: 1
cfn-lint:
config:
ignore_checks:
- W6001
AWS::CloudFormation::Interface:
ParameterGroups:
- Label:
default: General Properties
Parameters:
- pSRASolutionTagKey
- pSRASolutionName
- pSRAStagingS3BucketName
- Label:
default: CodeBuild Properties
Parameters:
- pCodeBuildProjectName
- pCodeBuildRoleName
- Label:
default: AWS Code Build Project - Lambda Function Properties
Parameters:
- pCodeBuildProjectLambdaRoleName
- pCodeBuildProjectLambdaFunctionName
- Label:
default: CFCT - Pipeline Configuration
Parameters:
- pPipelineApprovalStage
- pPipelineApprovalEmail
- pCodePipelineSource
- Label:
default: CFCT - AWS CodeCommit Setup (Applicable if 'AWS CodeCommit' was selected as the CodePipeline Source)
Parameters:
- pExistingRepository
- pCodeCommitRepositoryName
- pCodeCommitBranchName
- Label:
default: CFCT - AWS CloudFormation StackSets Configuration
Parameters:
- pRegionConcurrencyType
- pMaxConcurrentPercentage
- pFailureTolerancePercentage
- Label:
default: General Lambda Function Properties
Parameters:
- pCreateLambdaLogGroup
- pLambdaLogGroupRetention
- pLambdaLogGroupKmsKey
- pLambdaLogLevel
ParameterLabels:
pCodeCommitBranchName:
default: CodeCommit Branch Name
pCodeCommitRepositoryName:
default: CodeCommit Repository Name
pCodeBuildProjectName:
default: SRA CodeBuild Project Name
pCodeBuildRoleName:
default: SRA CodeBuild Role Name
pCodeBuildProjectLambdaRoleName:
default: SRA CodeBuild Project Lambda Role Name
pCodeBuildProjectLambdaFunctionName:
default: SRA CodeBuild Project Lambda Function Name
pCodePipelineSource:
default: AWS CodePipeline Source
pCreateLambdaLogGroup:
default: pCreateLambdaLogGroup
pExistingRepository:
default: Existing CodeCommit Repository?
pFailureTolerancePercentage:
default: Failure Tolerance Percentage
pLambdaLogGroupKmsKey:
default: (Optional) Lambda Log Group KMS Key
pLambdaLogGroupRetention:
default: Lambda Log Group Retention
pLambdaLogLevel:
default: Lambda Log Level
pMaxConcurrentPercentage:
default: Max Concurrent Percentage
pPipelineApprovalEmail:
default: Pipeline Approval Email Address
pPipelineApprovalStage:
default: Pipeline Approval Stage
pRegionConcurrencyType:
default: Region Concurrency Type
pSRASolutionName:
default: SRA Solution Name
pSRAStagingS3BucketName:
default: SRA Staging S3 Bucket Name
Parameters:
pCodeCommitBranchName:
Default: main
Description: Name of the branch in CodeCommit repository that contains custom Control Tower configuration.
MaxLength: 256
MinLength: 1
Type: String
pCodeCommitRepositoryName:
AllowedPattern: '^[\w-.]{1,100}(?<!\.git)$'
ConstraintDescription: Max 100 alphanumeric characters. Also special characters supported [_. -]. Name cannot end in '.git'.
Default: custom-control-tower-configuration
Description: Name of the CodeCommit repository that contains custom Control Tower configuration.
Type: String
pCodeBuildProjectName:
AllowedValues: [sra-cfct-codebuild-project]
Default: sra-cfct-codebuild-project
Description:
SRA CodeBuild project name
Type: String
pCodeBuildRoleName:
AllowedValues: [sra-cfct-codebuild-role]
Default: sra-cfct-codebuild-role
Description:
SRA CodeBuild role name
Type: String
pCodeBuildProjectLambdaRoleName:
AllowedPattern: '^[\w+=,.@-]{1,64}$'
ConstraintDescription: Max 64 alphanumeric characters. Also special characters supported [+, =, ., @, -].
Default: sra-cfct-codebuild-project-lambda-role
Description: Lambda execution role for starting the code build project
Type: String
pCodeBuildProjectLambdaFunctionName:
AllowedPattern: '^[\w-]{1,64}$'
ConstraintDescription: Max 64 alphanumeric characters. Also special characters supported [_, -]
Default: sra-cfct-codebuild-project-lambda
Description: Lambda function name for starting the code build project
Type: String
pCodePipelineSource:
AllowedValues: [Amazon S3, AWS CodeCommit]
Default: AWS CodeCommit
Description: Which AWS CodePipeline source provider do you want to select?
Type: String
pCreateLambdaLogGroup:
AllowedValues: ['Yes', 'No']
Default: 'No'
Description:
Indicates whether a CloudWatch Log Group should be explicitly created for the Lambda function, to allow for setting a Log Retention and/or KMS
Key for encryption.
Type: String
pExistingRepository:
AllowedValues: ['Yes', 'No']
Default: 'No'
Description: Are you using an existing CodeCommit repository that already contains custom Control Tower configuration?
Type: String
pFailureTolerancePercentage:
Default: 0
Description:
The percentage of accounts, per Region, for which this stack operation can fail before AWS CloudFormation stops the operation in that Region.
MaxValue: 100
MinValue: 0
Type: Number
pLambdaLogGroupKmsKey:
AllowedPattern: '^$|^arn:(aws[a-zA-Z-]*){1}:kms:[a-z0-9-]+:\d{12}:key\/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$'
ConstraintDescription: 'Key ARN example: arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab'
Default: ''
Description:
(Optional) KMS Key ARN to use for encrypting the Lambda logs data. If empty, encryption is enabled with CloudWatch Logs managing the server-side
encryption keys.
Type: String
pLambdaLogGroupRetention:
AllowedValues: [1, 3, 5, 7, 14, 30, 60, 90, 120, 150, 180, 365, 400, 545, 731, 1827, 3653]
Default: 14
Description: Specifies the number of days you want to retain log events
Type: String
pLambdaLogLevel:
AllowedValues: [INFO, ERROR, DEBUG]
Default: INFO
Description: Lambda Function Logging Level
Type: String
pMaxConcurrentPercentage:
Default: 100
Description: The maximum percentage of accounts in which to perform this operation at one time.
MaxValue: 100
MinValue: 1
Type: Number
pPipelineApprovalEmail:
AllowedPattern: '^$|^([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)$'
ConstraintDescription: Must be a valid email address.
Default: ''
Description: (Not required if Pipeline Approval Stage = 'No') Email for notifying that the CustomControlTower pipeline is waiting for an Approval
Type: String
pPipelineApprovalStage:
AllowedValues: ['Yes', 'No']
Default: 'No'
Description: Do you want to add a manual approval stage to the Custom Control Tower Configuration Pipeline?
Type: String
pRegionConcurrencyType:
AllowedValues: [PARALLEL, SEQUENTIAL]
Default: 'PARALLEL'
Description: Select the the concurrency type of deploying StackSets operations in Regions.
Type: String
pSRASolutionName:
AllowedValues: [sra-common-cfct-setup]
Default: sra-common-cfct-setup
Description: The SRA solution name. The Description value is the folder name of the solution
Type: String
pSRASolutionTagKey:
AllowedValues: [sra-solution]
Default: sra-solution
Description: The SRA solution tag key applied to all resources created by the solution that support tagging. The value is the pSRASolutionName.
Type: String
pSRAStagingS3BucketName:
AllowedPattern: '^([\w.-]{1,900})$|^(\/[\w.-]{1,900})*[\w.-]{1,900}$'
ConstraintDescription:
Must be alphanumeric or special characters [., _, -]. In addition, the slash character ( / ) used to delineate hierarchies in parameter names.
Default: /sra/staging-s3-bucket-name
Description:
SSM Parameter for SRA Staging S3 bucket name for the artifacts relevant to solution. (e.g., lambda zips, CloudFormation templates) S3 bucket
name can include numbers, lowercase letters, uppercase letters, and hyphens (-). It cannot start or end with a hyphen (-).
Type: AWS::SSM::Parameter::Value<String>
Rules:
PipelineApprovalEmailValidation:
RuleCondition: !Equals [!Ref pPipelineApprovalEmail, '']
Assertions:
- AssertDescription: "'Pipeline Approval Email Address' parameter is required if the 'Pipeline Approval Stage' parameter is set to 'Yes'."
Assert: !Equals [!Ref pPipelineApprovalStage, 'No']
Conditions:
cCreateLambdaLogGroup: !Equals [!Ref pCreateLambdaLogGroup, 'Yes']
cUsingKmsKey: !Not [!Equals [!Ref pLambdaLogGroupKmsKey, '']]
cUseGraviton: !Or
- !Equals [!Ref 'AWS::Region', ap-northeast-1]
- !Equals [!Ref 'AWS::Region', ap-south-1]
- !Equals [!Ref 'AWS::Region', ap-southeast-1]
- !Equals [!Ref 'AWS::Region', ap-southeast-2]
- !Equals [!Ref 'AWS::Region', eu-central-1]
- !Equals [!Ref 'AWS::Region', eu-west-1]
- !Equals [!Ref 'AWS::Region', eu-west-2]
- !Equals [!Ref 'AWS::Region', us-east-1]
- !Equals [!Ref 'AWS::Region', us-east-2]
- !Equals [!Ref 'AWS::Region', us-west-2]
Resources:
rCodeBuildProject:
Type: AWS::CodeBuild::Project
Properties:
Name: !Sub '${pCodeBuildProjectName}'
Artifacts:
Type: NO_ARTIFACTS
Description: "Codebuild project to get SRA code from github"
Environment:
ComputeType: BUILD_GENERAL1_SMALL
EnvironmentVariables:
- Name: AWS_DEFAULT_REGION
Value: !Ref AWS::Region
- Name: AWS_ACCOUNT_ID
Value: !Ref "AWS::AccountId"
Image: "aws/codebuild/standard:5.0"
PrivilegedMode: true
Type: "LINUX_CONTAINER"
ServiceRole: !GetAtt rCodeBuildRole.Arn
TimeoutInMinutes: 120
Source:
Type: NO_SOURCE
BuildSpec: !Sub |
version: 0.2
phases:
pre_build:
commands:
- echo Build started on `date`...
build:
commands:
- echo Build started on `date` in ${AWS::Region} region
- echo Downloading customizations-for-aws-control-tower.template template...
- wget https://raw.githubusercontent.com/aws-solutions/aws-control-tower-customizations/main/customizations-for-aws-control-tower.template
- echo Listing current directory...
- ls
- echo Showing current caller identity...
- aws sts get-caller-identity
- echo Copying customizations-for-aws-control-tower.template template to SRA staging bucket cloudformation template...
- aws s3 cp customizations-for-aws-control-tower.template s3://sra-staging-$AWS_ACCOUNT_ID-$AWS_DEFAULT_REGION/sra-common-cfct-setup/templates/
- git clone https://github.com/aws-samples/aws-security-reference-architecture-examples.git
post_build:
commands:
- echo Build completed on `date`
rCodeBuildRole:
Type: AWS::IAM::Role
Metadata:
cfn_nag:
rules_to_suppress:
- id: W11
reason: Allow * in resource when required
- id: W28
reason: The role name is defined to identify automation resources
Properties:
RoleName: !Sub '${pCodeBuildRoleName}'
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service:
- codebuild.amazonaws.com
Action:
- "sts:AssumeRole"
Policies:
- PolicyName: "logs-access"
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource:
- !Sub "arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/codebuild/*"
- PolicyName: "s3-staging-bucket-access"
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: "Allow"
Action:
- s3:PutObject
Resource:
- !Sub "arn:${AWS::Partition}:s3:::${pSRAStagingS3BucketName}/${pSRASolutionName}/templates"
- !Sub "arn:${AWS::Partition}:s3:::${pSRAStagingS3BucketName}/${pSRASolutionName}/templates/*"
rStartCodeBuildProjectCustomResource:
DependsOn: rCodeBuildProject
Type: Custom::LambdaCustomResource
Version: '1.0'
Properties:
ServiceToken: !GetAtt rStartCodeBuildProjectLambdaFunction.Arn
rStartCodeBuildProjectLambdaFunction:
Metadata:
cfn_nag:
rules_to_suppress:
- id: W58
reason: Lambda role provides access to CloudWatch Logs
- id: W89
reason: Lambda does not need to communicate with VPC resources.
- id: W92
reason: Lambda does not need reserved concurrent executions.
checkov:
skip:
- id: CKV_AWS_115
comment: Lambda does not need reserved concurrent executions.
- id: CKV_AWS_116
comment: DLQ not needed, as Lambda function only triggered by CloudFormation events.
- id: CKV_AWS_117
comment: Lambda does not need to communicate with VPC resources.
- id: CKV_AWS_173
comment: Environment variables are not sensitive.
Type: AWS::Lambda::Function
Properties:
FunctionName: !Ref pCodeBuildProjectLambdaFunctionName
Description: Start SRA codebuild project
Architectures: !If
- cUseGraviton
- [arm64]
- !Ref AWS::NoValue
Handler: index.lambda_handler
Role: !GetAtt rStartCodeBuildProjectLambdaRole.Arn
Runtime: python3.9
Timeout: 900
Environment:
Variables:
LOG_LEVEL: !Ref pLambdaLogLevel
CODE_BUILD_PROJECT_NAME: !Ref pCodeBuildProjectName
Tags:
- Key: !Ref pSRASolutionTagKey
Value: !Ref pSRASolutionName
Code:
ZipFile: |
# type: ignore
"""Custom Resource to start codebuild project.
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: MIT-0
"""
import logging
import os
import boto3
import cfnresponse
import time
from botocore.exceptions import ClientError
LOGGER = logging.getLogger(__name__)
log_level: str = os.environ.get("LOG_LEVEL", "INFO")
LOGGER.setLevel(log_level)
CODE_BUILD_PROJECT_NAME: str = os.environ.get("CODE_BUILD_PROJECT_NAME")
def start_build():
"""Start build job.
Returns:
Response data for custom resource
"""
management_account_session = boto3.Session()
codebuild_client = management_account_session.client("codebuild")
response = codebuild_client.start_build(projectName=CODE_BUILD_PROJECT_NAME)
LOGGER.info({"API_Call": "codebuild:StartBuild", "API_Response": response})
buildId = response["build"]["id"]
return wait_for_build([buildId], codebuild_client)
def wait_for_build(BuildId, client):
buildWaitStatus = "FAILURE_WAIT_TIMEOUT"
counter = 0
while counter < 30:
time.sleep(10)
counter = counter + 1
buildStatus = get_build_status(BuildId, client)
if buildStatus == "SUCCEEDED":
buildWaitStatus = "SUCCESS"
break
elif buildStatus == "FAILED" or buildStatus == "FAULT" or buildStatus == "STOPPED" or buildStatus == "TIMED_OUT":
buildWaitStatus = "BUILD " + buildStatus + " (check codebuild project cloudwatch log group for details)"
break
return buildWaitStatus
def get_build_status(buildId, client):
build = client.batch_get_builds(ids=buildId)
return build["builds"][0]["buildStatus"]
def create_event(event, context):
try:
data = {"data": start_build()}
if data["data"] == "SUCCESS":
cfnresponse.send(event, context, cfnresponse.SUCCESS, data, "CustomResourcePhysicalID")
else:
reason = f"See the details in CloudWatch Log Stream: '{context.log_group_name} and CloudFormation Events'"
cfnresponse.send(event, context, cfnresponse.FAILED, data, "CustomResourcePhysicalID")
except Exception:
LOGGER.exception("Unexpected!")
reason = f"See the details in CloudWatch Log Stream: '{context.log_group_name}'"
cfnresponse.send(event, context, cfnresponse.FAILED, {}, "CustomResourcePhysicalID", reason=reason)
return "CustomResourcePhysicalID"
def delete_event(event, context):
cfnresponse.send(event, context, cfnresponse.SUCCESS, {"delete_operation": "succeeded deleting"}, "CustomResourcePhysicalID")
def lambda_handler(event, context):
LOGGER.info(event)
if event["RequestType"] == "Create":
LOGGER.info("CREATE EVENT!!")
create_event(event, context)
if event["RequestType"] == "Update":
LOGGER.info("UPDATE EVENT!!")
if event["RequestType"] == "Delete":
LOGGER.info("DELETE EVENT!!")
delete_event(event, context)
rStartCodeBuildProjectLambdaLogGroup:
DeletionPolicy: Retain
Type: AWS::Logs::LogGroup
UpdateReplacePolicy: Retain
Condition: cCreateLambdaLogGroup
Properties:
LogGroupName: !Sub /aws/lambda/${pCodeBuildProjectLambdaFunctionName}
KmsKeyId: !If
- cUsingKmsKey
- !Ref pLambdaLogGroupKmsKey
- !Ref AWS::NoValue
RetentionInDays: !Ref pLambdaLogGroupRetention
rStartCodeBuildProjectLambdaRole:
Type: AWS::IAM::Role
Metadata:
cfn_nag:
rules_to_suppress:
# - id: W11
# reason: Allow * in resource when required
- id: W28
reason: The role name is defined to identify automation resources
Properties:
RoleName: !Ref pCodeBuildProjectLambdaRoleName
Description: !Sub Role for '${pCodeBuildProjectLambdaRoleName}' Lambda function
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action: sts:AssumeRole
Principal:
Service:
- lambda.amazonaws.com
Tags:
- Key: !Ref pSRASolutionTagKey
Value: !Ref pSRASolutionName
Policies:
- PolicyName: codebuild-access
PolicyDocument:
Version: 2012-10-17
Statement:
- Sid: codebuildStartBuild
Effect: Allow
Action:
- codebuild:StartBuild
- codebuild:BatchGetBuilds
Resource: !GetAtt rCodeBuildProject.Arn
- PolicyName: CloudWatchLogGroup-access
PolicyDocument:
Version: 2012-10-17
Statement:
- Sid: CloudWatchLogs
Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource: !Sub arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/${pCodeBuildProjectLambdaFunctionName}:log-stream:*
rCFCTStack:
Type: AWS::CloudFormation::Stack
DependsOn: rStartCodeBuildProjectCustomResource
Properties:
TemplateURL: !Sub https://${pSRAStagingS3BucketName}.s3.${AWS::Region}.${AWS::URLSuffix}/${pSRASolutionName}/templates/customizations-for-aws-control-tower.template
# TemplateURL: https://s3.amazonaws.com/solutions-reference/customizations-for-aws-control-tower/latest/custom-control-tower-initiation.template
Tags:
- Key: sra-solution
Value: !Ref pSRASolutionName
Parameters:
CodeCommitBranchName: !Ref pCodeCommitBranchName
CodeCommitRepositoryName: !Ref pCodeCommitRepositoryName
CodePipelineSource: !Ref pCodePipelineSource
ExistingRepository: !Ref pExistingRepository
FailureTolerancePercentage: !Ref pFailureTolerancePercentage
MaxConcurrentPercentage: !Ref pMaxConcurrentPercentage
PipelineApprovalEmail: !Ref pPipelineApprovalEmail
PipelineApprovalStage: !Ref pPipelineApprovalStage
RegionConcurrencyType: !Ref pRegionConcurrencyType