-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimage-builder.yaml
692 lines (658 loc) · 25.9 KB
/
image-builder.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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Parameters:
BuildInstanceType:
Type: CommaDelimitedList
Default: g4dn.2xlarge
Description: >-
Comma-delimited list of one or more instance types to select from when building
the image. Image Builder will select a type based on availability. The supplied
default is compatible with the AWS Free Tier.
ResourcesStackName:
Type: String
Resources:
InstanceRole:
Type: AWS::IAM::Role
Metadata:
Comment: Role to be used by instance during image build.
Properties:
ManagedPolicyArns:
- !Sub 'arn:${AWS::Partition}:iam::aws:policy/AmazonSSMManagedInstanceCore'
- !Sub 'arn:${AWS::Partition}:iam::aws:policy/EC2InstanceProfileForImageBuilder'
- !Sub 'arn:${AWS::Partition}:iam::aws:policy/EC2InstanceProfileForImageBuilderECRContainerBuilds'
- !Sub 'arn:${AWS::Partition}:iam::aws:policy/AmazonSNSFullAccess'
- !Sub 'arn:${AWS::Partition}:iam::aws:policy/AmazonEC2FullAccess'
AssumeRolePolicyDocument:
Statement:
- Action:
- sts:AssumeRole
Effect: Allow
Principal:
Service:
- ec2.amazonaws.com
Version: '2012-10-17'
Path: /executionServiceEC2Role/
InstanceRoleLoggingPolicy:
Type: AWS::IAM::Policy
Metadata:
Comment: Allows the instance to save log files to an S3 bucket.
Properties:
PolicyName: ImageBuilderLogBucketPolicy
Roles:
- !Ref 'InstanceRole'
PolicyDocument:
Version: '2012-10-17'
Statement:
- Action:
- s3:PutObject
Effect: Allow
Resource:
- !Sub
- arn:${AWS::Partition}:s3:::${BUCKET}/*
- BUCKET: !ImportValue
Fn::Sub: ${ResourcesStackName}-Bucket
InstanceProfile:
Type: AWS::IAM::InstanceProfile
Properties:
Path: /executionServiceEC2Role/
Roles:
- !Ref 'InstanceRole'
UbuntuServerImageInfrastructureConfiguration:
Type: AWS::ImageBuilder::InfrastructureConfiguration
Properties:
Name: !Sub 'UbuntuServer20-Image-Infrastructure-Configuration-${AWS::StackName}'
InstanceProfileName: !Ref 'InstanceProfile'
InstanceTypes: !Ref 'BuildInstanceType'
Logging:
S3Logs:
S3BucketName: !ImportValue
Fn::Sub: ${ResourcesStackName}-Bucket
S3KeyPrefix: !Join
- '-'
- - imagebuilder
- !Ref 'AWS::StackName'
SecurityGroupIds:
- !ImportValue
Fn::Sub: ${ResourcesStackName}-SecurityGroup
SnsTopicArn: !Ref 'ImageBuilderSNSTopic'
InstallEFSUtilsComponent:
Type: AWS::ImageBuilder::Component
Properties:
Name: !Sub 'EFSUtils-${AWS::StackName}'
Version: '0.0.2'
Description: Install the latest EFS Utils.
ChangeDescription: First version
Platform: Linux
Data: |
name: InstallEFSUtils
description: Downloads and Installs EFS Utils
schemaVersion: 1.0
phases:
- name: build
steps:
- name: Apt
action: ExecuteBash
inputs:
commands:
- "sudo apt-get update"
- "sudo apt-get -y install python3-pip awscli binutils jq zip"
- name: InstallFolder
action: ExecuteBash
inputs:
commands:
- echo "$HOME/install"
- name: CreateInstallFolder
action: CreateFolder
inputs:
- path: '{{ build.InstallFolder.outputs.stdout }}'
- name: EFSUtils
action: ExecuteBash
inputs:
commands:
- "cd {{ build.InstallFolder.outputs.stdout }}"
- "git clone https://github.com/aws/efs-utils"
- "cd efs-utils"
- "sudo bash ./build-deb.sh"
- "sudo apt-get -y install ./build/amazon-efs-utils*.deb"
- "sudo -u ubuntu -i mkdir -p efs"
- name: Cleanup
action: DeleteFolder
inputs:
- path: '{{ build.InstallFolder.outputs.stdout }}'
force: true
- name: EFSFolder
action: ExecuteBash
inputs:
commands:
- echo "/home/ubuntu/efs"
- name: CreateUbuntuUserEFSFolder
action: CreateFolder
inputs:
- path: '{{ build.EFSFolder.outputs.stdout }}'
owner: ubuntu
group: ubuntu
InstallCFNInitComponent:
Type: AWS::ImageBuilder::Component
Properties:
Name: !Sub 'CFNInit-${AWS::StackName}'
Version: '0.0.2'
Description: Install the latest CFNInit.
ChangeDescription: First version
Platform: Linux
Data: |
name: InstallCFNInit
description: Downloads and Installs cfn init
schemaVersion: 1.0
phases:
- name: build
steps:
- name: InstallFolder
action: ExecuteBash
inputs:
commands:
- echo "$HOME/install"
- name: CreateInstallFolder
action: CreateFolder
inputs:
- path: '{{ build.InstallFolder.outputs.stdout }}'
- name: CFNInit
action: ExecuteBash
inputs:
commands:
- "cd {{ build.InstallFolder.outputs.stdout }}"
- "sudo curl -o awscfnboot.tar.gz https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-py3-latest.tar.gz"
- "sudo tar -zxf awscfnboot.tar.gz"
- "sudo python3 -m pip install ./aws-cfn-bootstrap-2.0"
- name: Cleanup
action: DeleteFolder
inputs:
- path: '{{ build.InstallFolder.outputs.stdout }}'
force: true
InstallDeepRacerComponent:
Type: AWS::ImageBuilder::Component
Properties:
Name: !Sub 'DeepRacer-${AWS::StackName}'
Version: '0.0.2'
Description: Install the latest DeepRacer config.
ChangeDescription: First version
Platform: Linux
Data: |
name: InstallDeepRacer
description: Downloads and Installs deepracer community config
schemaVersion: 1.0
phases:
- name: build
steps:
- name: CloneCommunityRepo
action: ExecuteBash
inputs:
commands:
- "apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1804/x86_64/7fa2af80.pub"
- "sudo -u ubuntu -i git clone https://github.com/jdmcdonagh/deepracer-for-cloud.git"
- name: BuildFromCommunityRepo
action: ExecuteBash
inputs:
commands:
- "sudo -u ubuntu -i bash -c 'cd /home/ubuntu/deepracer-for-cloud && ./bin/prepare.sh'"
- name: Reboot
action: Reboot
onFailure: Abort
maxAttempts: 2
inputs:
delaySeconds: 60
- name: init
action: ExecuteBash
inputs:
commands:
- "sudo -u ubuntu -i bash -c 'cd /home/ubuntu/deepracer-for-cloud && ./bin/init.sh -c aws -a gpu'"
CreateLogsComponent:
Type: AWS::ImageBuilder::Component
Properties:
Name: !Sub 'CreateLogScript-${AWS::StackName}'
Version: '0.0.2'
Description: Create Logs script.
ChangeDescription: First version
Platform: Linux
Data: |
name: CreateLogs
description: logs to s3
schemaVersion: 1.0
phases:
- name: build
steps:
- name: CopyLogs
action: CreateFile
inputs:
- path: /home/ubuntu/bin/create_logs.sh
permissions: 775
owner: ubuntu
group: ubuntu
content: |
#!/bin/bash
cd $DR_DIR/data/logs
rm *.log *.zip
echo hello;echo hello
for name in $(docker ps --format \{\{.Names}\}); do
docker logs ${name} >& ${name}.log
done
zip robomaker_log deepracer-0_robomaker.1.*.log
aws s3 cp robomaker_log.zip s3://$DR_LOGS_COPY_S3_BUCKET/
InstallDeepRacerDockerImagesScriptComponent:
Type: AWS::ImageBuilder::Component
Properties:
Name: !Sub 'DeepRacerDockerImagesScript-${AWS::StackName}'
Version: '0.0.2'
Description: Install the latest DeepRacer docker images script.
ChangeDescription: First version
Platform: Linux
Data: |
name: InstallDeepRacerDockerImages
description: Downloads and Installs deepracer docker images script
schemaVersion: 1.0
phases:
- name: build
steps:
- name: PullDeepracerDockerImagesScript
action: CreateFile
inputs:
- path: /home/ubuntu/bin/pull-docker-images.sh
permissions: 775
owner: ubuntu
group: ubuntu
content: |
REGISTRY=https://index.docker.io/v2
REGISTRY_AUTH=https://auth.docker.io
REGISTRY_SERVICE=registry.docker.io
IMAGE_NAME=""
DOCKER_BIN=docker
TAGS_FILTER=""
VERBOSE=0
TAGS_LIMIT=1
ignore_404=0
OPTIND=1
while getopts "n:f:v" opt; do
case "$opt" in
n) IMAGE_NAME="$OPTARG"
;;
f) TAGS_FILTER="$OPTARG"
;;
v) VERBOSE=1
;;
esac
done
shift $((OPTIND-1))
[ "${1:-}" = "--" ] && shift
if [ -z $IMAGE_NAME ]; then
echo Requires Image Name
exit 1;
else
if [[ $VERBOSE -eq 1 ]]; then
echo Using IMAGE_NAME: $IMAGE_NAME
fi
fi
function do_curl_get () {
local URL="$1"
shift
local array=("$@")
HTTP_RESPONSE="$(curl -sSL --write-out "HTTPSTATUS:%{http_code}" \
-H "Content-Type: application/json;charset=UTF-8" \
"${array[@]}" \
-X GET "$URL")"
# echo $HTTP_RESPONSE
HTTP_BODY=$(echo "$HTTP_RESPONSE" | sed -E 's/HTTPSTATUS\:[0-9]{3}$//')
HTTP_STATUS=$(echo "$HTTP_RESPONSE" | tr -d '\n' | sed -E 's/.*HTTPSTATUS:([0-9]{3})$/\1/')
# Check that the http status is 200
if [[ "$HTTP_STATUS" -ne 200 ]]; then
if [[ "$ignore_404" -eq 0 ]]; then
if [[ "$VERBOSE" -eq 0 ]]; then
echo -e "\\nError $HTTP_STATUS from: $URL\\n"
else
echo -e "\\nError $HTTP_STATUS from: $URL\\nHTTP_BODY: $HTTP_BODY\\n"
fi
fi
fi
}
# Get AUTH token
# This cannot be: ("")
CURL_AUTH=()
CURL_URL="$REGISTRY_AUTH/token?service=${REGISTRY_SERVICE##*(//)}&scope=repository:$IMAGE_NAME:pull"
do_curl_get "$CURL_URL" "${CURL_AUTH[@]}"
AUTH=$(echo "$HTTP_BODY" | jq --raw-output .token)
# Get Tags
CURL_AUTH=( -H "Authorization: Bearer $AUTH" )
CURL_URL="$REGISTRY/$IMAGE_NAME/tags/list"
do_curl_get "$CURL_URL" "${CURL_AUTH[@]}"
TAGS_CURL=$(echo "$HTTP_BODY")
TAGS_temp=$(echo "$TAGS_CURL"|jq --arg TAGS_FILTER "$TAGS_FILTER" -r '.tags[]|select(.|endswith($TAGS_FILTER))'|grep -vi windows|sort -r --version-sort)
TAG=$(echo "$TAGS_temp"|sed -n 1,"$TAGS_LIMIT"p)
docker pull $IMAGE_NAME:$TAG
ExpandRootVolumeComponent:
Type: AWS::ImageBuilder::Component
Properties:
Name: !Sub 'ExpandRootVolume-${AWS::StackName}'
Version: '0.0.2'
Description: Expand root volume.
ChangeDescription: First version
Platform: Linux
Data: |
name: ExpandRootVolume
description: Expands root volume
schemaVersion: 1.0
phases:
- name: build
steps:
- name: ExpandRootVolume
action: ExecuteBash
inputs:
commands:
- |
id=$(curl http://169.254.169.254/latest/meta-data/instance-id)
vol_id=$(aws ec2 describe-instances --region us-east-1 --instance-ids $id --query 'Reservations[0].Instances[0].BlockDeviceMappings[0].Ebs.VolumeId' --output text)
aws ec2 modify-volume --size 40 --volume-id $vol_id --region us-east-1
PullDeepracerDockerImagesComponent:
Type: AWS::ImageBuilder::Component
Properties:
Name: !Sub 'PullDeepracerDockerImages-${AWS::StackName}'
Version: '0.0.2'
Description: Pull newest deepracer docker images.
ChangeDescription: First version
Platform: Linux
Data: |
name: PullDeepracerDockerImages
description: Pull deepracer docker images
schemaVersion: 1.0
phases:
- name: build
steps:
- name: PullDeepracerDockerImages
action: ExecuteBash
inputs:
commands:
- "bash -c '/home/ubuntu/bin/pull-docker-images.sh -n awsdeepracercommunity/deepracer-robomaker -v -f -gpu'"
- "bash -c '/home/ubuntu/bin/pull-docker-images.sh -n awsdeepracercommunity/deepracer-robomaker -v -f -cpu-avx2'"
- "bash -c '/home/ubuntu/bin/pull-docker-images.sh -n awsdeepracercommunity/deepracer-sagemaker -v -f -gpu'"
- "bash -c '/home/ubuntu/bin/pull-docker-images.sh -n awsdeepracercommunity/deepracer-rlcoach -v'"
DeepracerS3URIComponent:
Type: AWS::ImageBuilder::Component
Properties:
Name: !Sub 'DeepRacerS3URI-${AWS::StackName}'
Version: '0.0.2'
Description: Install the latest DeepRacer docker images script.
ChangeDescription: First version
Platform: Linux
Data: !Sub
- |
name: DeepRacerS3URI
description: Creates an envrironment variable for DR_S3_URI
schemaVersion: 1.0
phases:
- name: build
steps:
- name: DeepRacerS3URI
action: CreateFile
inputs:
- path: /etc/profile.d/s3_uri.sh
permissions: 775
owner: root
group: root
content: |
export DR_S3_URI=${BUCKET}
export DEEPRACER_S3_URI=${BUCKET}
export PATH=/home/ubuntu/bin:$PATH
- BUCKET: !ImportValue
Fn::Sub: ${ResourcesStackName}-Bucket
SafeTerminationComponent:
Type: AWS::ImageBuilder::Component
Properties:
Name: !Sub 'SafeTermination-${AWS::StackName}'
Version: '0.0.2'
Description: Install script to terminate training and upload model.
ChangeDescription: First version
Platform: Linux
Data: |
name: SafeTermination
description: terminates training
schemaVersion: 1.0
phases:
- name: build
steps:
- name: SafeTermination
action: CreateFile
inputs:
- path: /home/ubuntu/bin/safe_termination.sh
permissions: 775
owner: ubuntu
group: ubuntu
content: |
#!/bin/bash
. /home/ubuntu/deepracer-for-cloud/bin/activate.sh
dr-stop-training
dr-upload-model -bf
aws s3 cp /tmp/logs/ s3://$DEEPRACER_S3_URI/$DR_LOCAL_S3_MODEL_PREFIX/logs/ --recursive
rm -rf /tmp/logs/
UbuntuServerForDeepRacerImageRecipe:
Type: AWS::ImageBuilder::ImageRecipe
Properties:
Name: !Sub 'UbuntuServerForDeepRacer-${AWS::StackName}'
Version: '0.0.2'
ParentImage: !Sub 'arn:${AWS::Partition}:imagebuilder:${AWS::Region}:aws:image/ubuntu-server-18-lts-x86/x.x.x'
Components:
- ComponentArn: !Ref 'CreateLogsComponent'
- ComponentArn: !Ref 'DeepracerS3URIComponent'
- ComponentArn: !Ref 'SafeTerminationComponent'
- ComponentArn: !Ref 'InstallEFSUtilsComponent'
- ComponentArn: !Ref 'ExpandRootVolumeComponent'
- ComponentArn: !Ref 'InstallDeepRacerDockerImagesScriptComponent'
- ComponentArn: !Ref 'InstallCFNInitComponent'
- ComponentArn: !Ref 'InstallDeepRacerComponent'
- ComponentArn: !Ref 'PullDeepracerDockerImagesComponent'
UbuntuServerImagePipeline:
Type: AWS::ImageBuilder::ImagePipeline
Properties:
Description: DeepRacer image build pipeline
ImageRecipeArn: !Ref 'UbuntuServerForDeepRacerImageRecipe'
InfrastructureConfigurationArn: !Ref 'UbuntuServerImageInfrastructureConfiguration'
Name: !Sub 'DeepRacerImageBuildPipeline-${AWS::StackName}'
Tags:
BuildStack: !Sub '${AWS::StackName}'
Name: DeepRacer
Schedule:
PipelineExecutionStartCondition: EXPRESSION_MATCH_ONLY
ScheduleExpression: cron(0 0 * * ? *)
SNSPermissionToInvokeUpdateParameter:
Type: AWS::Lambda::Permission
Properties:
FunctionName: !GetAtt 'UpdateSSMParameter.Arn'
Action: lambda:InvokeFunction
Principal: sns.amazonaws.com
SourceArn: !Ref 'ImageBuilderSNSTopic'
SNSPermissionToInvokeDeleteOldAMIs:
Type: AWS::Lambda::Permission
Properties:
FunctionName: !GetAtt 'DeleteOldAMIs.Arn'
Action: lambda:InvokeFunction
Principal: sns.amazonaws.com
SourceArn: !Ref 'ImageBuilderSNSTopic'
ImageBuilderSNSTopic:
Type: AWS::SNS::Topic
Properties:
DisplayName: Image Builder
Subscription:
- Protocol: lambda
Endpoint: !GetAtt 'UpdateSSMParameter.Arn'
- Protocol: lambda
Endpoint: !GetAtt 'DeleteOldAMIs.Arn'
TopicPolicy:
Type: AWS::SNS::TopicPolicy
Properties:
PolicyDocument:
Statement:
- Sid: AllowServices
Effect: Allow
Principal: '*'
Action:
- sns:Publish
- sns:Subscribe
Resource: '*'
Topics:
- !Ref 'ImageBuilderSNSTopic'
UpdateSSMParameter:
Type: AWS::Serverless::Function
Properties:
Handler: index.handler
Runtime: python3.7
InlineCode: !Sub |
import json
import boto3
import logging
import os
logger = logging.getLogger()
logger.setLevel(logging.INFO)
ssm_client = boto3.client('ssm')
ec2_client = boto3.client('ec2')
ssm_parameter_name = os.getenv('ParameterPath')
def handler(event, context):
logger.info('Printing event: {}'.format(event))
process_sns_event(event)
return None
def process_sns_event(event):
for record in (event['Records']):
event_message = record['Sns']['Message']
message_json = json.loads(event_message)
image_state = (message_json['state']['status'])
if (image_state == 'AVAILABLE'):
logger.info('Image is available')
ami = message_json['outputResources']['amis'][0]
ec2_client.create_tags(Resources=[ami['image']], Tags=[{'Key': 'Name', 'Value': 'DeepRacer'}, {'Key': 'Stack', 'Value': '${AWS::StackName}'}])
recipe_name = message_json['name']
logger.info('AMI ID: {}'.format(ami['image']))
response = ssm_client.put_parameter(
Name=ssm_parameter_name,
Description='Latest AMI ID',
Value=ami['image'],
Type='String',
Overwrite=True,
Tier='Standard'
)
logger.info('SSM Updated: {}'.format(response))
#add tags to the SSM parameter
ssm_client.add_tags_to_resource(ResourceType='Parameter', ResourceId=ssm_parameter_name, Tags=[ { 'Key': 'Source', 'Value': 'Image Builder' } ] )
return None
Description: Update SSM Parameter with the latest AMI
MemorySize: 256
Timeout: 300
AutoPublishAlias: live
Environment:
Variables:
ParameterPath: !ImportValue
Fn::Sub: ${ResourcesStackName}-AMIParameter
Policies:
- Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- ssm:PutParameter
- ssm:AddTagsToResource
- ssm:GetParameters
- ec2:*
Resource: '*'
DeleteOldAMIs:
Type: AWS::Serverless::Function
Properties:
Handler: index.handler
Runtime: python3.7
InlineCode: !Sub |
import json
import boto3
import logging
import os
logger = logging.getLogger()
logger.setLevel(logging.INFO)
ssm_client = boto3.client('ssm')
ec2_client = boto3.client('ec2')
ssm_parameter_name = os.getenv('ParameterPath')
def handler(event, context):
logger.info('Printing event: {}'.format(event))
process_sns_event(event)
return None
def delete_ebs_snapshots():
paginator = ec2_client.get_paginator('describe_snapshots')
filters = {'OwnerIds': ['${AWS::AccountId}']}
for page in paginator.paginate(**filters):
for snapshot in page['Snapshots']:
try:
print('SNAPSHOT')
print(snapshot)
ec2_client.delete_snapshot(SnapshotId=snapshot['SnapshotId'])
print('DELETED EBS SNAPSHOT')
print(snapshot['SnapshotId'])
except Exception as e:
print('EXCEPTION DELETING SNAPSHOT')
print(e)
def get_image_by_parameter():
try:
return ssm_client.get_parameter(Name=ssm_parameter_name)['Parameter']['Value']
except:
pass
return None
def get_amis_with_my_stack(current_image):
stack_name = '${AWS::StackName}'
filters = [
{
'Name': 'is-public',
'Values': [
'false'
]
},
{
'Name': 'state',
'Values': [
'available'
]
},
{
'Name': 'tag:Stack',
'Values': [
'${AWS::StackName}'
]
}
]
ignore_images = [current_image]
image_from_parameters = get_image_by_parameter()
if image_from_parameters:
ignore_images.append(image_from_parameters)
images = ec2_client.describe_images(Filters=filters, Owners=['${AWS::AccountId}'])['Images']
images = list(map(lambda x: x['ImageId'], images))
images = list(filter(lambda x: x not in ignore_images, images))
for image in images:
logger.info('Deregistring Image: {}'.format(image))
try:
ec2_client.deregister_image(ImageId=image)
except:
pass
def process_sns_event(event):
for record in (event['Records']):
event_message = record['Sns']['Message']
message_json = json.loads(event_message)
image_state = (message_json['state']['status'])
if (image_state == 'AVAILABLE'):
current_image = message_json['outputResources']['amis'][0]['image']
get_amis_with_my_stack(current_image)
delete_ebs_snapshots()
return None
Description: Delete old AMIs
MemorySize: 256
Timeout: 900
AutoPublishAlias: live
Environment:
Variables:
ParameterPath: !ImportValue
Fn::Sub: ${ResourcesStackName}-AMIParameter
Policies:
- Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- ssm:GetParameters
- ec2:*
Resource: '*'