44Attributes:
55 LOG_LEVEL (str):
66 REGION_OVERRIDE (str): If provided, this value will override the default AWS region.
7- logger (logging.Logger):
7+ logger (logging.Logger): The logger to be used throughout execution of the AWS Lambda.
88
99"""
1010import datetime
1111import json
1212import logging
1313import os
14+ from typing import Any , Dict , List
1415
1516import boto3
1617from botocore .exceptions import ClientError
1718
19+ from .exceptions import ImproperlyConfigured , InvalidPayload
20+
1821LOG_LEVEL = getattr (logging , os .environ .get ("CLOUDENDURE_LOGLEVEL" , "INFO" ))
1922REGION_OVERRIDE = os .environ .get ("CLOUDENDURE_REGION_OVERRIDE" , "" )
2023
2326logger .setLevel (LOG_LEVEL )
2427
2528
26- def send_sqs_message (imageinfo ):
27- """Sends a SQS message with the AMI information
28- that was created from the migrated instance
29- that passed testing post migration in CloudEndure
29+ def send_sqs_message (image_info : Dict ) -> bool :
30+ """Send a SQS message.
31+
32+ The message includes the AMI information that was created from the migrated
33+ instance that passed testing post migration in CloudEndure.
34+
35+ Raises:
36+ ClientError: The exception is raised in the event of a boto3 client error.
37+ ImproperlyConfigured: The exception is raised in the event of missing or invalid
38+ environment configuration settings.
39+
40+ Returns:
41+ bool: Whether or not the message has been sent successfully.
42+
3043 """
44+ queue_url = os .environ .get ("QueueURL" , "" )
45+ if not queue_url :
46+ raise ImproperlyConfigured ("Missing environment variable: QueueURL" )
47+
3148 try :
32- message = json .dumps (imageinfo )
49+ message = json .dumps (image_info )
3350 sqsclient = boto3 .client ("sqs" )
34- sqsclient .send_message (QueueUrl = os .environ ["QueueURL" ], MessageBody = message )
35-
36- except ClientError as err :
37- logger .error (err .response )
51+ sqsclient .send_message (QueueUrl = queue_url , MessageBody = message )
52+ except ClientError as e :
53+ logger .error (e .response )
54+ return False
55+ except ImproperlyConfigured as e :
56+ logger .error (e )
57+ return False
58+ return True
3859
3960
40- def create_ami (project_id , instance_id ) :
61+ def create_ami (project_id : str , instance_id : str ) -> bool :
4162 """Create an AMI from the specified instance.
4263
64+ Args:
65+ project_id (str): The ID associated with the Project.
66+ instance_id (str): The ID associated with the AWS instance.
67+
68+ Raises:
69+ ClientError: The exception is raised in the event of a boto3 client error.
70+
71+ Returns:
72+ bool: Whether or not the AMI has been created successfully.
73+
4374 """
4475 try :
4576 _ec2_client = boto3 .client ("ec2" )
@@ -53,7 +84,10 @@ def create_ami(project_id, instance_id):
5384 NoReboot = True ,
5485 )
5586 logger .info ("AMI Id: %s" , ec2_image )
56- _filters = [{"Name" : "resource-id" , "Values" : [instance_id ]}]
87+ _filters : List [Dict ] = [{
88+ "Name" : "resource-id" ,
89+ "Values" : [instance_id ],
90+ }]
5791
5892 # Tag the newly created AMI by getting the tags of the migrated instance to copy to the AMI.
5993 ec2_tags = _ec2_client .describe_tags (Filters = _filters )
@@ -69,26 +103,46 @@ def create_ami(project_id, instance_id):
69103
70104 except ClientError as err :
71105 logger .error (err .response )
106+ return False
107+ return True
72108
73109
74- def lambda_handler (event , context ):
75- """Lambda entry point"""
76- logger .info (event )
110+ def lambda_handler (event : Dict [str , Any ], context : Dict [str , Any ]) -> bool :
111+ """Define the AWS Lambda entry point and handler.
77112
78- try :
79- json_sns_message = json .loads (event ["Records" ][0 ]["Sns" ]["Message" ])
113+ Args:
114+ event (str): The event performed against Lambda.
115+ context (dict): The context of the request performed against Lambda.
80116
81- if json_sns_message ["Pass" ] != "True" :
82- logger .error (
83- "%s did not pass post migration testing! Not creating an AMI."
84- % (json_sns_message ["instanceId" ])
85- )
117+ Raises:
118+ ClientError: The exception is raised in the event of a boto3 client error.
119+ InvalidPayload: The exception is raised in the event of an invalid payload.
120+
121+ Returns:
122+ bool: Whether or not the lambda function has executed successfully.
123+
124+ """
125+ logger .debug (event )
126+
127+ event_records = event .get ("Records" , [])
128+ if not event_records :
129+ return False
86130
131+ try :
132+ event_message = event_records [0 ].get ("Sns" , {}).get ("Message" , "" )
133+ json_sns_message = json .loads (event_message )
134+ instance_id : str = json_sns_message .get ("instanceId" , "" )
135+ project_id : str = json_sns_message .get ("projectId" , "" )
136+
137+ if json_sns_message .get ("Pass" , "NA" ) != "True" :
138+ raise InvalidPayload (f"{ instance_id } did not pass post migration testing! Not creating an AMI." )
87139 else :
88- logger .info (
89- "%s passed post migration testing. Creating an AMI."
90- % (json_sns_message ["instanceId" ])
91- )
92- create_ami ("" , json_sns_message ["instanceId" ])
93- except ClientError as err :
94- logger .error (err .response )
140+ logger .info ("%s passed post migration testing. Creating an AMI." % (instance_id ))
141+ create_ami (project_id , instance_id )
142+ except ClientError as e :
143+ logger .error (e .response )
144+ return False
145+ except InvalidPayload as e :
146+ logger .error (e )
147+ return False
148+ return True
0 commit comments