11# This file is part of pycloudlib. See LICENSE file for license information.
22"""AWS EC2 Cloud type."""
3+ import re
4+
35import botocore
46
57from pycloudlib .cloud import BaseCloud , ImageType
@@ -111,13 +113,11 @@ def _get_name_for_image_type(
111113 )
112114 if release in LTS_RELEASES :
113115 return "{}/ubuntu-{}{}-*-server-*" .format (
114- base_location , release ,
115- "-daily" if daily else ""
116+ base_location , release , "-daily" if daily else ""
116117 )
117118
118119 return "{}/ubuntu-{}{}-*" .format (
119- base_location , release ,
120- "-daily" if daily else ""
120+ base_location , release , "-daily" if daily else ""
121121 )
122122
123123 if image_type == ImageType .PRO :
@@ -196,7 +196,39 @@ def daily_image(
196196 )
197197 return image ["ImageId" ]
198198
199- def image_serial (self , image_id ):
199+ def _find_image_serial (
200+ self , image_id , image_type : ImageType = ImageType .GENERIC
201+ ):
202+ owner = self ._get_owner (image_type = image_type )
203+ filters = [
204+ {
205+ "Name" : "image-id" ,
206+ "Values" : (image_id ,),
207+ }
208+ ]
209+
210+ images = self .client .describe_images (
211+ Owners = [owner ],
212+ Filters = filters ,
213+ )
214+
215+ if not images .get ("Images" ):
216+ raise Exception ("Could not find image: {}" .format (image_id ))
217+
218+ image_name = images ["Images" ][0 ].get ("Name" , "" )
219+ serial_regex = r"ubuntu/.*/.*/.*-(?P<serial>\d+)$"
220+ serial_match = re .match (serial_regex , image_name )
221+
222+ if not serial_match :
223+ raise Exception (
224+ "Could not find image serial for image: {}" .format (image_id )
225+ )
226+
227+ return serial_match .groupdict ().get ("serial" )
228+
229+ def image_serial (
230+ self , image_id , image_type : ImageType = ImageType .GENERIC
231+ ):
200232 """Find the image serial of a given EC2 image ID.
201233
202234 Args:
@@ -209,11 +241,7 @@ def image_serial(self, image_id):
209241 self ._log .debug (
210242 "finding image serial for EC2 Ubuntu image %s" , image_id
211243 )
212- filters = ["id=%s" % image_id ]
213- image_info = self ._streams_query (filters , daily = True )
214- if not image_info :
215- image_info = self ._streams_query (filters , daily = False )
216- return image_info [0 ]["version_name" ]
244+ return self ._find_image_serial (image_id , image_type )
217245
218246 def delete_image (self , image_id ):
219247 """Delete an image.
0 commit comments