Skip to content

Commit

Permalink
EC2:run_instances() now validates the provided SecurityGroup (#5486)
Browse files Browse the repository at this point in the history
  • Loading branch information
bblommers authored Sep 19, 2022
1 parent b0e7814 commit b9f5eca
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
11 changes: 8 additions & 3 deletions moto/ec2/models/instances.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
InvalidInstanceIdError,
InvalidInstanceTypeError,
InvalidParameterValueErrorUnknownAttribute,
InvalidSecurityGroupNotFoundError,
OperationNotPermitted4,
)
from ..utils import (
Expand Down Expand Up @@ -596,19 +597,23 @@ def add_instances(self, image_id, count, user_data, security_group_names, **kwar
):
if settings.EC2_ENABLE_INSTANCE_TYPE_VALIDATION:
raise InvalidInstanceTypeError(kwargs["instance_type"])
new_reservation = Reservation()
new_reservation.id = random_reservation_id()

security_groups = [
self.get_security_group_by_name_or_id(name) for name in security_group_names
]

for sg_id in kwargs.pop("security_group_ids", []):
if isinstance(sg_id, str):
security_groups.append(self.get_security_group_from_id(sg_id))
sg = self.get_security_group_from_id(sg_id)
if sg is None:
raise InvalidSecurityGroupNotFoundError(sg_id)
security_groups.append(sg)
else:
security_groups.append(sg_id)

new_reservation = Reservation()
new_reservation.id = random_reservation_id()

self.reservations[new_reservation.id] = new_reservation

tags = kwargs.pop("tags", {})
Expand Down
13 changes: 13 additions & 0 deletions tests/test_ec2/test_instances.py
Original file line number Diff line number Diff line change
Expand Up @@ -688,6 +688,19 @@ def test_get_instances_filtering_by_ni_private_dns():
reservations[0]["Instances"].should.have.length_of(1)


@mock_ec2
def test_run_instances_with_unknown_security_group():
client = boto3.client("ec2", region_name="us-east-1")
sg_id = f"sg-{str(uuid4())[0:6]}"
with pytest.raises(ClientError) as exc:
client.run_instances(
ImageId=EXAMPLE_AMI_ID, MinCount=1, MaxCount=1, SecurityGroupIds=[sg_id]
)
err = exc.value.response["Error"]
err["Code"].should.equal("InvalidGroup.NotFound")
err["Message"].should.equal(f"The security group '{sg_id}' does not exist")


@mock_ec2
def test_get_instances_filtering_by_instance_group_name():
client = boto3.client("ec2", region_name="us-east-1")
Expand Down

0 comments on commit b9f5eca

Please sign in to comment.