diff --git a/moto/ec2/models.py b/moto/ec2/models.py index c2bfbf058..656f9556c 100644 --- a/moto/ec2/models.py +++ b/moto/ec2/models.py @@ -1034,8 +1034,7 @@ class Instance(TaggedEC2Resource, BotoInstance, CloudFormationModel): zone = self._placement.zone subnet = self.ec2_backend.get_default_subnet(availability_zone=zone) - group_id = nic.get("SecurityGroupId") - group_ids = [group_id] if group_id else [] + group_ids = nic.get("SecurityGroupId") or [] if security_groups: group_ids.extend([group.id for group in security_groups]) diff --git a/tests/test_ec2/test_instances.py b/tests/test_ec2/test_instances.py index 97e706283..37336bf0e 100644 --- a/tests/test_ec2/test_instances.py +++ b/tests/test_ec2/test_instances.py @@ -1360,6 +1360,46 @@ def test_run_instance_with_nic_preexisting_boto3(): instance_eni["PrivateIpAddresses"][0]["PrivateIpAddress"].should.equal(private_ip) +@mock_ec2 +def test_run_instance_with_new_nic_and_security_groups(): + ec2 = boto3.resource("ec2", "us-west-1") + client = boto3.client("ec2", "us-west-1") + security_group1 = ec2.create_security_group( + GroupName=str(uuid4()), Description="n/a" + ) + security_group2 = ec2.create_security_group( + GroupName=str(uuid4()), Description="n/a" + ) + + instance = ec2.create_instances( + ImageId=EXAMPLE_AMI_ID, + MinCount=1, + MaxCount=1, + NetworkInterfaces=[ + { + "DeviceIndex": 0, + "Groups": [security_group1.group_id, security_group2.group_id], + } + ], + )[0] + + nii = instance.network_interfaces_attribute[0]["NetworkInterfaceId"] + + all_enis = client.describe_network_interfaces(NetworkInterfaceIds=[nii])[ + "NetworkInterfaces" + ] + all_enis.should.have.length_of(1) + + instance_enis = instance.network_interfaces_attribute + instance_enis.should.have.length_of(1) + instance_eni = instance_enis[0] + + instance_eni["Groups"].should.have.length_of(2) + set([group["GroupId"] for group in instance_eni["Groups"]]).should.equal( + set([security_group1.id, security_group2.id]) + ) + + @mock_ec2 def test_instance_with_nic_attach_detach_boto3(): ec2 = boto3.resource("ec2", "us-west-1")