Skip to content

Commit a2f585f

Browse files
authored
ENH gets latest image if more than one (#472)
* enable getting the newest image if there are more than one with the same string contained in the name * cleanup * cleanup * clean up * typo * update the tests
1 parent a332e0c commit a2f585f

File tree

2 files changed

+12
-13
lines changed

2 files changed

+12
-13
lines changed

ramp-engine/ramp_engine/aws/api.py

+10-11
Original file line numberDiff line numberDiff line change
@@ -251,26 +251,25 @@ def launch_ec2_instances(config, nb=1):
251251
def _get_image_id(config, image_name):
252252
sess = _get_boto_session(config)
253253
client = sess.client('ec2')
254+
255+
# get all the images with the given image_name in the name
254256
result = client.describe_images(Filters=[
255257
{
256258
'Name': 'name',
257-
'Values': [
258-
image_name
259-
]
259+
'Values': [f'{image_name}*'
260+
],
260261
}
261262
])
263+
262264
images = result['Images']
263265
if len(images) == 0:
264266
raise ValueError(
265267
'No image corresponding to the name "{}"'.format(image_name))
266-
elif len(images) > 1:
267-
raise ValueError(
268-
'Multiple images corresponding to the name "{}".'
269-
' Please fix that'.format(image_name))
270-
else:
271-
image = images[0]
272-
image_id = image['ImageId']
273-
return image_id
268+
269+
# get only the newest image if there are more than one
270+
image = sorted(images, key=lambda x: x['CreationDate'],
271+
reverse=True)[0]
272+
return image['ImageId']
274273

275274

276275
def terminate_ec2_instance(config, instance_id):

ramp-engine/ramp_engine/tests/test_aws.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -191,7 +191,7 @@ def test_launch_ec2_instances(boto_session_cls, use_spot_instance):
191191
session = boto_session_cls.return_value
192192
client = session.client.return_value
193193
describe_images = client.describe_images
194-
images = {"Images": [{"ImageId": 1}]}
194+
images = {"Images": [{"ImageId": 1, "CreationDate": 123}]}
195195
describe_images.return_value = images
196196
config = read_config(os.path.join(HERE, '_aws_config.yml'))
197197

@@ -218,7 +218,7 @@ def test_creating_instances(boto_session_cls, caplog,
218218
session = boto_session_cls.return_value
219219
client = session.client.return_value
220220
describe_images = client.describe_images
221-
images = {"Images": [{"ImageId": 1}]}
221+
images = {"Images": [{"ImageId": 1, "CreationDate": 123}]}
222222
describe_images.return_value = images
223223

224224
error = {

0 commit comments

Comments
 (0)