diff --git a/moto/ec2/responses/key_pairs.py b/moto/ec2/responses/key_pairs.py index 0e5fc47ae..d03a10e38 100644 --- a/moto/ec2/responses/key_pairs.py +++ b/moto/ec2/responses/key_pairs.py @@ -2,6 +2,7 @@ from jinja2 import Template from moto.core.responses import BaseResponse from moto.ec2.models import ec2_backend from moto.ec2.exceptions import InvalidIdError +from moto.ec2.utils import keypair_names_from_querystring class KeyPairs(BaseResponse): @@ -23,8 +24,15 @@ class KeyPairs(BaseResponse): return Template(DELETE_KEY_PAIR_RESPONSE).render(success=success) def describe_key_pairs(self): - template = Template(DESCRIBE_KEY_PAIRS_RESPONSE) - return template.render(keypairs=ec2_backend.describe_key_pairs()) + names = keypair_names_from_querystring(self.querystring) + try: + keypairs = ec2_backend.describe_key_pairs(names) + except InvalidIdError as exc: + template = Template(CREATE_KEY_PAIR_NOT_FOUND) + return template.render(keypair_id=exc.id), dict(status=400) + else: + template = Template(DESCRIBE_KEY_PAIRS_RESPONSE) + return template.render(keypairs=keypairs) def import_key_pair(self): raise NotImplementedError('KeyPairs.import_key_pair is not yet implemented') @@ -58,6 +66,11 @@ CREATE_KEY_PAIR_INVALID_NAME = """ """ +CREATE_KEY_PAIR_NOT_FOUND = """ +InvalidKeyPair.NotFoundThe keypair '{{ keypair_id }}' does not exist.f4f76e81-8ca5-4e61-a6d5-a4a96EXAMPLE +""" + + DELETE_KEY_PAIR_RESPONSE = """ 59dbff89-35bd-4eac-99ed-be587EXAMPLE {{ success }} diff --git a/moto/ec2/utils.py b/moto/ec2/utils.py index 385f4cced..dc5697838 100644 --- a/moto/ec2/utils.py +++ b/moto/ec2/utils.py @@ -116,6 +116,15 @@ def filters_from_querystring(querystring_dict): return response_values +def keypair_names_from_querystring(querystring_dict): + keypair_names = [] + for key, value in querystring_dict.iteritems(): + if 'KeyName' in key: + keypair_names.append(value[0]) + return keypair_names + + + filter_dict_attribute_mapping = { 'instance-state-name': 'state' } diff --git a/tests/test_ec2/test_key_pairs.py b/tests/test_ec2/test_key_pairs.py index 18bc0865b..e43718ade 100644 --- a/tests/test_ec2/test_key_pairs.py +++ b/tests/test_ec2/test_key_pairs.py @@ -31,6 +31,9 @@ def test_key_pairs_create_two(): assert len(kps) == 2 assert kps[0].name == 'foo' assert kps[1].name == 'bar' + kps = conn.get_all_key_pairs('foo') + assert len(kps) == 1 + assert kps[0].name == 'foo' @mock_ec2