1515# {
1616# "copy_ami" : "ami-123456",
1717# "kms_id" : "GUID",
18- # "wait_time": 60
18+ # "wait_time": 60,
19+ # "region" : optional region
1920# }
2021
2122
@@ -24,42 +25,52 @@ def lambda_handler(event: Dict[str, Any], context: Any) -> str:
2425 print ("Received event: " + json .dumps (event , indent = 2 ))
2526
2627 copy_ami : str = event ["copy_ami" ]
27-
28- # Access the image that needs to be split
29- image = ec2_res .Image (copy_ami )
30-
31- root_drive : Dict [str , Any ] = {}
32- drives : Dict [str , Any ] = {}
33-
34- # separate the root drive from the other drives
35- devices : List [Any ] = image .block_device_mappings
36- for device in devices :
37- if "Ebs" in device :
38- if device ["DeviceName" ] == image .root_device_name :
39- print (f"Found Root! { device } " )
40- root_drive : Dict [str , Any ] = device
41- else :
42- drives [device ["DeviceName" ]] = device ["Ebs" ]
43-
44- # have to remove the encrypted flag
45- del root_drive ["Ebs" ]["Encrypted" ]
46-
47- # create a new AMI with only the root
48- response = ec2_res .register_image (
49- Architecture = image .architecture ,
50- BlockDeviceMappings = [root_drive ],
51- Name = f"root-{ copy_ami } " ,
52- RootDeviceName = image .root_device_name ,
53- VirtualizationType = image .virtualization_type ,
54- )
55-
56- root_ami = response .id
57-
58- for drive in drives :
59- print (drives [drive ])
60- ec2_res .create_tags (
61- Resources = [root_ami ],
62- Tags = [{"Key" : f"Drive-{ drive } " , "Value" : json .dumps (drives [drive ])}],
28+ region : str = event .get ("region" )
29+ if region :
30+ ec2_res = boto3 .resource ("ec2" , region )
31+
32+ try :
33+ # Access the image that needs to be split
34+ image = ec2_res .Image (copy_ami )
35+
36+ root_drive : Dict [str , Any ] = {}
37+ drives : Dict [str , Any ] = {}
38+
39+ # separate the root drive from the other drives
40+ devices : List [Any ] = image .block_device_mappings
41+ for device in devices :
42+ if "Ebs" in device :
43+ if device ["DeviceName" ] == image .root_device_name :
44+ print (f"Found Root! { device } " )
45+ root_drive : Dict [str , Any ] = device
46+ else :
47+ drives [device ["DeviceName" ]] = device ["Ebs" ]
48+
49+ # have to remove the encrypted flag
50+ del root_drive ["Ebs" ]["Encrypted" ]
51+
52+ # create a new AMI with only the root
53+ response = ec2_res .register_image (
54+ Architecture = image .architecture ,
55+ BlockDeviceMappings = [root_drive ],
56+ Name = f"root-{ copy_ami } " ,
57+ RootDeviceName = image .root_device_name ,
58+ VirtualizationType = image .virtualization_type ,
6359 )
6460
61+ root_ami = response .id
62+
63+ for drive in drives :
64+ print (drives [drive ])
65+ ec2_res .create_tags (
66+ Resources = [root_ami ],
67+ Tags = [{"Key" : f"Drive-{ drive } " , "Value" : json .dumps (drives [drive ])}],
68+ )
69+
70+ # clean up original image
71+ image .deregister ()
72+ except Exception as e :
73+ print (e )
74+ return ""
75+
6576 return root_ami
0 commit comments