Skip to content

Commit 360f6c8

Browse files
authored
Merge pull request #90 from hsohail94/hsohail94/ami-id-ssm-update-lambda
feat: Add option to create Lambda to add latest build's AMI ID to Parameter Store
2 parents 4e79b31 + c71d0e0 commit 360f6c8

File tree

7 files changed

+601
-43
lines changed

7 files changed

+601
-43
lines changed

API.md

Lines changed: 13 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
import json
2+
import boto3
3+
import logging
4+
import os
5+
6+
logger = logging.getLogger()
7+
logger.setLevel(logging.INFO)
8+
9+
session = boto3.session.Session()
10+
11+
12+
def lambda_handler(event, context):
13+
logger.info('Printing event: {}'.format(event))
14+
process_sns_event(event)
15+
return None
16+
17+
18+
def process_sns_event(event):
19+
for record in event['Records']:
20+
event_message = record['Sns']['Message']
21+
22+
ssm_parameter_name = os.getenv('SSM_PATH')
23+
24+
# convert the event message to json
25+
message_json = json.loads(event_message)
26+
27+
# obtain the image state
28+
image_state = message_json['state']['status']
29+
30+
# update the SSM parameter if the image state is available
31+
if image_state == 'AVAILABLE':
32+
logger.info('Image is available')
33+
34+
recipe_name = message_json['name']
35+
36+
for ami in message_json['outputResources']['amis']:
37+
# obtain ami id
38+
logger.info('AMI ID: {}'.format(ami['image']))
39+
40+
# update SSM parameter
41+
ssm_client = session.client(
42+
service_name='ssm',
43+
region_name=ami['region'],
44+
)
45+
response = ssm_client.put_parameter(
46+
Name=ssm_parameter_name,
47+
Description='Latest AMI ID',
48+
Value=ami['image'],
49+
Type='String',
50+
Overwrite=True,
51+
Tier='Standard',
52+
)
53+
logger.info('SSM Updated: {}'.format(response))
54+
55+
# add tags to the SSM parameter
56+
ssm_client.add_tags_to_resource(
57+
ResourceType='Parameter',
58+
ResourceId=ssm_parameter_name,
59+
Tags=[
60+
{'Key': 'Source', 'Value': 'EC2 Image Builder'},
61+
{'Key': 'AMI_REGION', 'Value': ami['region']},
62+
{'Key': 'AMI_ID', 'Value': ami['image']},
63+
{'Key': 'AMI_NAME', 'Value': ami['name']},
64+
{'Key': 'RECIPE_NAME', 'Value': recipe_name},
65+
{
66+
'Key': 'SOURCE_PIPELINE_ARN',
67+
'Value': message_json['sourcePipelineArn'],
68+
},
69+
],
70+
)
71+
72+
# end of Lambda function
73+
return None

0 commit comments

Comments
 (0)