forked from aws-deepracer-community/deepracer-on-the-spot
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbase-resources.yaml
508 lines (469 loc) · 16.4 KB
/
base-resources.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
AWSTemplateFormatVersion: "2010-09-09"
Description: Setup base requirements for DeepRacer on the Spot
Parameters:
MyIPAddress:
Type: String
RuleNumber:
Type: String
NetworkAclId:
Type: String
Outputs:
InstanceProfile:
Description: Instance Profile
Value: !Ref InstanceProfile
Export:
Name:
!Sub '${AWS::StackName}-InstanceProfile'
DeepRacerServiceRole:
Description: DeepRacer Service Role
Value: !GetAtt DeepRacerServiceRole.Arn
Export:
Name:
!Sub '${AWS::StackName}-DeepRacerServiceRole'
Region:
Description: Region in use
Value: !Ref AWS::Region
Export:
Name:
!Sub '${AWS::StackName}-Region'
Bucket:
Description: S3 Bucket
Value: !Ref Bucket
Export:
Name:
!Sub '${AWS::StackName}-Bucket'
SecurityGroup:
Description: Security Group
Value: !GetAtt SecurityGroup.GroupId
Export:
Name:
!Sub '${AWS::StackName}-SecurityGroup'
NetworkAclId:
Description: Network ACL Id
Value: !Ref NetworkAclId
Export:
Name:
!Sub '${AWS::StackName}-NetworkAclId'
InterruptionNotification:
Description: Interruption Notification
Value: !Ref InterruptionNotification
Export:
Name:
!Sub '${AWS::StackName}-InterruptionNotification'
FutureTimeCronExpressionLambdaArn:
Description: Lambda arn of a function that generates a cloudwatch schedule compatible cron expression for a future time, measured in 'minutes in the future'
Value: !GetAtt FutureTimeCronExpressionLambda.Arn
Export:
Name:
!Sub '${AWS::StackName}-FutureTimeCronExpressionLambdaArn'
TerminationLambdaArn:
Description: Lambda arn of a function that safely terminates an instance
Value: !GetAtt TerminationLambda.Arn
Export:
Name:
!Sub '${AWS::StackName}-TerminationLambdaArn'
Resources:
Bucket:
Type: 'AWS::S3::Bucket'
Properties:
LifecycleConfiguration:
Rules:
- Id: Delete
Prefix: imagebuilder
Status: Enabled
ExpirationInDays: 1
BucketAccessPolicy:
Type: 'AWS::S3::BucketPolicy'
Properties:
Bucket: !Ref Bucket
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: 'Allow'
Principal:
AWS:
- !GetAtt InstanceRole.Arn
Service:
- deepracer.amazonaws.com
Action:
- 's3:GetObject'
- 's3:ListBucket'
- 's3:PutObject'
- 's3:PutObjectAcl'
Resource:
- !Join
- ''
- - 'arn:aws:s3:::'
- !Ref Bucket
- !Join
- ''
- - 'arn:aws:s3:::'
- !Ref Bucket
- '/*'
SecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Allow access from My IP Address
SecurityGroupIngress:
Type: AWS::EC2::SecurityGroupIngress
Properties:
GroupName: !Ref SecurityGroup
IpProtocol: -1
CidrIp: !Sub '${MyIPAddress}/32'
NACLEntry:
Type: AWS::EC2::NetworkAclEntry
Properties:
NetworkAclId: !Ref NetworkAclId
CidrBlock: !Sub '${MyIPAddress}/32'
Protocol: '-1'
RuleAction: allow
RuleNumber: !Ref RuleNumber
InstanceRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- ec2.amazonaws.com
Action:
- sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/AmazonEC2FullAccess
- arn:aws:iam::aws:policy/AmazonSSMFullAccess
Policies:
- PolicyName: !Sub '${AWS::StackName}-inline-policy'
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- ssmmessages:CreateControlChannel
- ssmmessages:CreateDataChannel
- ssmmessages:OpenControlChannel
- ssmmessages:OpenDataChannel
Resource: '*'
- Effect: Allow
Action:
- kms:*
- s3:*
- sns:*
- ssm:*
- iam:DeleteRolePolicy
- iam:DetachRolePolicy
- iam:DeleteRole
- events:DeleteRule
- events:RemoveTargets
- lambda:RemovePermission
- lambda:DeleteFunction
- lambda:InvokeFunction
Resource: '*'
- Effect: Allow
Action:
- cloudformation:DeleteStack
Resource:
- !Sub "arn:${AWS::Partition}:cloudformation:${AWS::Region}:${AWS::AccountId}:stack/*"
- Effect: Allow
Action:
- iam:passRole
Resource:
- !GetAtt DeepRacerServiceRole.Arn
InstanceProfile:
Type: AWS::IAM::InstanceProfile
Properties:
Roles:
- !Ref InstanceRole
DeepRacerServiceRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- deepracer.amazonaws.com
Action:
- sts:AssumeRole
Policies:
- PolicyName: !Sub '${AWS::StackName}-inline-policy'
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- s3:ListAllMyBuckets
Resource: '*'
- Effect: Allow
Action:
- s3:GetBucketPolicy
- s3:PutBucketPolicy
- s3:ListBucket
- s3:GetBucketAcl
- s3:GetObject
- s3:GetObjectVersion
- s3:GetObjectAcl
- s3:GetBucketLocation
Resource:
- !Join
- ''
- - 'arn:aws:s3:::'
- !Ref Bucket
- !Join
- ''
- - 'arn:aws:s3:::'
- !Ref Bucket
- '/*'
InterruptionNotification:
Type: AWS::SNS::Topic
Properties:
DisplayName: InterruptionNotification
TopicPolicy:
Type: AWS::SNS::TopicPolicy
Properties:
PolicyDocument:
Statement:
- Sid: AllowServices
Effect: Allow
Principal: '*'
Action:
- sns:Publish
- sns:Subscribe
Resource: '*'
Topics:
- !Ref 'InterruptionNotification'
FutureTimeCronExpressionLambda:
Type: AWS::Lambda::Function
Properties:
Handler: index.handler
Role: !GetAtt FutureTimeCronExpressionLambdaRole.Arn
Runtime: python3.11
Code:
ZipFile: |
import cfnresponse
import datetime
def handler(event, context):
physical_resource_id = 'FutureTimeCronExpression'
response_code = cfnresponse.SUCCESS
response_data = {'cron_expression': ''}
if event.get('RequestType', '') == 'Delete':
if 'ResponseURL' in event:
cfnresponse.send(event, context, response_code, response_data, physical_resource_id)
print(response_data)
return response_data
try:
ttl = int(event['ResourceProperties']['ttl'])
except:
ttl = 60 * 12 # 12 hours
expires = datetime.datetime.now() + datetime.timedelta(minutes=ttl)
cron_expression = f"cron({expires.minute} {expires.hour} {expires.day} {expires.month} ? {expires.year})"
print(F"cron expression: {cron_expression}")
response_data['cron_expression'] = cron_expression
if 'ResponseURL' in event:
cfnresponse.send(event, context, response_code, response_data, physical_resource_id)
print(response_data)
return response_data
FutureTimeCronExpressionLambdaRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
FutureTimeCronExpressionLambdaPermission:
Type: AWS::Lambda::Permission
Properties:
FunctionName: !GetAtt FutureTimeCronExpressionLambda.Arn
Action: lambda:InvokeFunction
Principal: cloudformation.amazonaws.com
SourceAccount: !Ref AWS::AccountId
TerminationLambda:
Type: AWS::Lambda::Function
Properties:
Role: !GetAtt TerminationLambdaRole.Arn
Handler: index.handler
Runtime: python3.11
Timeout: 900
Code:
ZipFile: !Sub |
import json
import boto3
import logging
import os
from botocore.exceptions import ClientError
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def execute_safe_termination(INSTANCE):
ssm_client = boto3.client('ssm')
asg_client = boto3.client('autoscaling')
instance=INSTANCE
try:
asg_info = asg_client.describe_auto_scaling_groups(
AutoScalingGroupNames=[
instance,
],
)
instance = asg_info['AutoScalingGroups'][0]['Instances'][0]['InstanceId']
except:
print("Instance isn't part of an ASG, will execute on individual EC2 instance")
try:
response = ssm_client.send_command(
InstanceIds=[instance],
DocumentName='AWS-RunShellScript',
Parameters={'commands': ['su - ubuntu bash -lc /home/ubuntu/bin/safe_termination.sh']},
CloudWatchOutputConfig={'CloudWatchOutputEnabled': True},
TimeoutSeconds=60)
command_id = response['Command']['CommandId']
print(f'Running commands on instance {instance}. Command id: {command_id}')
waiter = ssm_client.get_waiter('command_executed')
waiter.wait(CommandId=command_id, InstanceId=instance, WaiterConfig={'Delay': 30, 'MaxAttempts': 3})
except ssm_client.exceptions.InvalidInstanceId:
print("SSM agent not running.")
except ClientError as e:
print(e.response['Error']['Message'])
def initiate_stack_deletion(stack):
cfn_client = boto3.client('cloudformation')
cfn_client.delete_stack(StackName=stack)
def notify(stack, instance):
sns_client = boto3.client('sns')
topic = '${InterruptionNotification}'
sns_client.publish(TopicArn=topic, Message=f'Training has completed for instance: {instance} stack: {stack}')
def handler(event, context):
instance = event['instance']
stack = event['stack']
execute_safe_termination(instance)
initiate_stack_deletion(stack)
notify(stack, instance)
logger.info('Printing event: {}'.format(event))
return None
notification_topic = os.environ['INTERRUPTION_NOTIFICATION']
TerminationLambdaRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/AmazonEC2FullAccess
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
Policies:
- PolicyName: !Sub '${AWS::StackName}-termination-lambda-policy'
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- ssmmessages:CreateControlChannel
- ssmmessages:CreateDataChannel
- ssmmessages:OpenControlChannel
- ssmmessages:OpenDataChannel
- iam:*
- sns:*
- ssm:*
- events:*
- lambda:*
- cloudformation:DeleteStack
Resource: '*'
QuotaLambda:
Type: AWS::Lambda::Function
Properties:
Role: !GetAtt QuotaLambdaRole.Arn
Handler: index.handler
Runtime: python3.11
Timeout: 30
Code:
ZipFile: !Sub |
import boto3
import logging
import cfnresponse
from botocore.exceptions import ClientError
logger = logging.getLogger()
logger.setLevel(logging.INFO)
client = boto3.client('service-quotas')
def handler(event, context):
if event['RequestType'] == 'Create':
try:
existing_spot_quota = client.get_service_quota(
ServiceCode='ec2',
QuotaCode='L-3819A6DF'
)
if existing_spot_quota['Quota']['Value'] < 16:
spot_response = client.request_service_quota_increase(
ServiceCode='ec2',
QuotaCode='L-3819A6DF',
DesiredValue=16
)
else:
spot_response="Existing spot quota is already sufficient"
existing_ondemand_quota = client.get_service_quota(
ServiceCode='ec2',
QuotaCode='L-DB2E81BA'
)
if existing_ondemand_quota['Quota']['Value'] < 16:
ondemand_response = client.request_service_quota_increase(
ServiceCode='ec2',
QuotaCode='L-DB2E81BA',
DesiredValue=16
)
else:
ondemand_response="Existing on-demand quota is already sufficient"
logger.info('Printing event: {}'.format(spot_response))
logger.info('Printing event: {}'.format(ondemand_response))
responseData = {}
responseData['Data'] = str(spot_response) + ", " +str(ondemand_response)
cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData)
except ClientError as e:
responseData = {}
responseData['Data'] = e.response['Error']['Message'] + ". Likely you have an existing quota request in process, check AWS Support console."
print(e.response['Error']['Message'])
cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData)
else:
responseData = {}
responseData['Data'] = 'Event not a create event, nothing to do'
cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData)
QuotaLambdaRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/AmazonEC2FullAccess
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
- arn:aws:iam::aws:policy/IAMFullAccess
Policies:
- PolicyName: !Sub '${AWS::StackName}-quota-lambda-policy'
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- servicequotas:*
Resource: '*'
QuotaInvoke:
Type: AWS::CloudFormation::CustomResource
Version: "1.0"
Properties:
ServiceToken: !GetAtt QuotaLambda.Arn
FunctionName: !Ref QuotaLambda