-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontrol-tower-management.yml
318 lines (311 loc) · 13 KB
/
control-tower-management.yml
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
AWSTemplateFormatVersion: '2010-09-09'
Description: AWS Control Tower Lifecycle Events for Couchbase
Parameters:
ManagedTemplateURL:
Description: Base URL for Couchbase's CloudFormation template for managed accounts
Type: String
Default: 'https://cb-control-tower.s3.us-west-2.amazonaws.com/control-tower-managed.yml'
SharedServicesTemplateURL:
Description: Base URL for Couchbase's CloudFormation template for Shared Services account
Type: String
Default: 'https://cb-control-tower.s3.us-west-2.amazonaws.com/control-tower-shared-services-stackset.yml'
CouchbaseBootstrapParameter:
Description: System Manager Parameter that contains the couchbase server rally host url
Type: String
CouchbaseSecretArn:
Description: Secret manager secret that contains Couchbase Server Connection information
Type: String
SharedServicesAccountId:
Description: Account Id of the Shared Services account that contains Couchbase Server
Type: String
Resources:
ControlTowerKMSKey:
Type: AWS::KMS::Key
Properties:
Description: This is KMS Key Id used to encrypt/decrypt the Secret
EnableKeyRotation: true
KeyPolicy:
Version: '2012-10-17'
Id: key-default-1
Statement:
- Sid: Allow administration of the key
Effect: Allow
Principal:
AWS: !Sub 'arn:aws:iam::${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: !Sub '${AWS::AccountId}'
Action:
- kms:Encrypt
- kms:Decrypt
- kms:ReEncrypt
- kms:GenerateDataKey
- kms:CreateGrant
- kms:DescribeKey
Resource: '*'
Condition:
StringEquals:
kms:ViaService: !Sub 'secretsmanager.${AWS::Region}.amazonaws.com'
kms:CallerAccount: !Sub '${AWS::AccountId}'
ControlTowerKMSAlias:
Type: AWS::KMS::Alias
Properties:
AliasName: !Sub 'alias/Control-Tower-${AWS::StackName}'
TargetKeyId: !Ref 'ControlTowerKMSKey'
StackSet:
Type: AWS::CloudFormation::StackSet
Properties:
Description: StackSet for creating Integration Role
StackSetName: CB-MemberStackSet
Parameters:
- ParameterKey: ParentAccountId
ParameterValue: SomeValue
PermissionModel: SELF_MANAGED
AdministrationRoleARN: !Join [':', ['arn:aws:iam:', !Ref 'AWS::AccountId', 'role/service-role/AWSControlTowerStackSetRole']]
ExecutionRoleName: AWSControlTowerExecution
Capabilities:
- CAPABILITY_NAMED_IAM
- CAPABILITY_IAM
- CAPABILITY_AUTO_EXPAND
TemplateURL: !Ref 'ManagedTemplateURL'
ManagementStackSet:
Type: AWS::CloudFormation::StackSet
Properties:
Description: StackSet for creating Couchbase Secret and Role
StackSetName: CB-SharedServicesStackSet
Parameters:
- ParameterKey: ChildAccountId
ParameterValue: SomeValue
- ParameterKey: Password
ParameterValue: SomePassword
- ParameterKey: Bootstrap
ParameterValue: SomeUrl
- ParameterKey: CouchbaseSecretArn
ParameterValue: SomeValue
PermissionModel: SELF_MANAGED
AdministrationRoleARN: !Join [':', ['arn:aws:iam:', !Ref 'AWS::AccountId', 'role/service-role/AWSControlTowerStackSetRole']]
ExecutionRoleName: AWSControlTowerExecution
Capabilities:
- CAPABILITY_NAMED_IAM
- CAPABILITY_IAM
- CAPABILITY_AUTO_EXPAND
TemplateURL: !Ref 'SharedServicesTemplateURL'
CaptureControlTowerLifeCycleEvents:
Type: AWS::Events::Rule
Properties:
Description: Capture Control Tower LifeCycle Events for Couchbase and Trigger an Action
EventPattern:
detail:
eventName:
- CreateManagedAccount
- UpdateManagedAccount
- EnableGuardrail
- DisableGuardrail
- SetupLandingZone
- UpdateLandingZone
- RegisterOrganizationalUnit
- DeregisterOrganizationalUnit
eventSource:
- controltower.amazonaws.com
detail-type:
- AWS Service Event via CloudTrail
source:
- aws.controltower
Name: CouchbaseCaptureControlTowerLifeCycleEvents
State: ENABLED
Targets:
- Arn: !GetAtt 'TriggerCustomizationsOnLifeCycleEvent.Arn'
Id: IDCaptureControlTowerLifeCycleEvents
TriggerCustomizationsOnLifeCycleEvent:
Type: AWS::Lambda::Function
Properties:
Environment:
Variables:
COUCHBASE_BOOTSTRAP_PARAM: !Ref 'CouchbaseBootstrapParameter'
COUCHBASE_SECRET_ARN: !Ref 'CouchbaseSecretArn'
MANAGED_TEMPLATE_URL: !Ref 'ManagedTemplateURL'
SHARED_SERVICES_ACCOUNT_ID: !Ref 'SharedServicesAccountId'
Code:
ZipFile: |
import json
import os
import boto3
import logging
import requests
from requests.auth import HTTPBasicAuth
import string
import random
logger = logging.getLogger()
logger.setLevel(logging.INFO)
managedStackSet = "CB-MemberStackSet"
managementStackSet = "CB-SharedServicesStackSet"
result = {"ResponseMetadata":{"HTTPStatusCode":"400"}}
secretsmanager = boto3.client('secretsmanager')
cloudformation = boto3.client('cloudformation')
parameterstore = boto3.client('ssm')
bootstrapParamName = os.environ['COUCHBASE_BOOTSTRAP_PARAM']
couchbaseSecretArn = os.environ['COUCHBASE_SECRET_ARN']
templateUrl = os.environ['MANAGED_TEMPLATE_URL']
sharedServicesAccountNumber = os.environ['SHARED_SERVICES_ACCOUNT_ID']
logger.info('Template Url: {}'.format(templateUrl))
logger.info('couchbaseSecretArn: {}'.format(couchbaseSecretArn))
logger.info('bootstrap Param: {}'.format(bootstrapParamName))
def password_generator(size=20, chars=string.ascii_uppercase+string.digits+string.ascii_lowercase+"@%+!#$^?~-_"):
return ''.join(random.SystemRandom().choice(chars) for _ in range(size))
def get_secret_value(key=couchbaseSecretArn):
output = {}
output = json.loads(secretsmanager.get_secret_value(SecretId=couchbaseSecretArn)['SecretString'])
return(output)
def lambda_handler(event, context):
masterAcct = event['account']
eventDetails = event['detail']
regionName = eventDetails['awsRegion']
eventName = eventDetails['eventName']
srvEventDetails = eventDetails['serviceEventDetails']
passwd = password_generator()
if eventName == 'CreateManagedAccount':
newAccInfo = {}
logger.info('Event Processed Sucessfully')
if eventName == 'CreateManagedAccount':
newAccInfo = srvEventDetails['createManagedAccountStatus']
cmdStatus = newAccInfo['state']
if cmdStatus == 'SUCCEEDED':
'Sucessful event recieved'
accId = newAccInfo['account']['accountId']
try:
# 2. Create Stackset for Shared Services Account (Create Secret and role) will need to override parameters
result = cloudformation.create_stack_instances(StackSetName=managementStackSet, Accounts=[sharedServicesAccountNumber], Regions=[regionName], ParameterOverrides=[{
'ParameterKey': 'Password',
'ParameterValue': passwd,
'UsePreviousValue': False
}, {
'ParameterKey': 'Bootstrap',
'ParameterValue': bootstrapParamName,
'UsePreviousValue': False
}, {
'ParameterKey': 'ChildAccountId',
'ParameterValue': accId,
'UsePreviousValue': False
}, {
'ParameterKey': 'CouchbaseSecretArn',
'ParameterValue': couchbaseSecretArn,
'UsePreviousValue': False
}])
except Exception as e:
logger.error('Unable to launch in: {}, REASON: {}'.format(managementStackSet, e))
try:
# 3. Create StackSet for Managed Account Passing parameters: ParentAccountId and the IAmRole name which should be CB-Access-{accId}
result = cloudformation.create_stack_instances(StackSetName=managedStackSet, Accounts=[accId], Regions=[regionName], ParameterOverrides=[{
'ParameterKey': 'ParentAccountId',
'ParameterValue': sharedServicesAccountNumber,
'UsePreviousValue': False
}])
logger.info('Processed {} Sucessfully'.format(managedStackSet))
except Exception as e:
logger.error('Unable to launch in:{}, REASON: {}'.format(managedStackSet, e))
else:
'Unsucessful event recieved'
logger.info('Unsucessful Event Recieved. SKIPPING :{}'.format(event))
return(False)
else:
logger.info('Control Tower Event Captured :{}'.format(event))
Handler: index.lambda_handler
MemorySize: 256
Role: !GetAtt 'TriggerLifecycleEventLambdaRole.Arn'
Runtime: python3.7
Timeout: 60
TriggerLifecycleEventLambdaRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Sid: AllowLambdaAssumeRole
Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
Policies:
- PolicyName: CouchbaseLifecycleLambdaGetSecretPolicy
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Resource:
- !Ref 'CouchbaseSecretArn'
Action:
- secretsmanager:GetSecretValue
- PolicyName: CouchbaseLifecycleSSMParameterPolicy
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- ssm:GetParameter
Resource:
- '*'
- PolicyName: CouchbaseLifecycleCreatePolicy
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- secretsmanager:CreateSecret
- iam:CreateRole
- iam:CreatePolicy
Resource:
- '*'
- PolicyName: StacksetCreationPolicy
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- sts:AssumeRole
Resource:
- !Join
- ':'
- - 'arn:aws:iam:'
- !Ref 'AWS::AccountId'
- role/service-role/AWSControlTowerStackSetRole
- Effect: Allow
Action:
- cloudformation:CreateStackInstances
Resource:
- !Join
- ':'
- - arn:aws:cloudformation
- !Ref 'AWS::Region'
- !Ref 'AWS::AccountId'
- stackset/CB-MemberStackSet:*
- !Join
- ':'
- - arn:aws:cloudformation
- !Ref 'AWS::Region'
- !Ref 'AWS::AccountId'
- stackset/CB-SharedServicesStackSet:*
ManagedPolicyArns:
- !Sub 'arn:${AWS::Partition}:iam::aws:policy/ReadOnlyAccess'
- !Sub 'arn:${AWS::Partition}:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole'
PermissionForEventsToInvokeLambdachk:
Type: AWS::Lambda::Permission
Properties:
Action: lambda:InvokeFunction
FunctionName: !GetAtt 'TriggerCustomizationsOnLifeCycleEvent.Arn'
Principal: events.amazonaws.com
SourceArn: !GetAtt 'CaptureControlTowerLifeCycleEvents.Arn'