From 687b9ddef70e08993bac253e0823ddc427f69f2b Mon Sep 17 00:00:00 2001 From: Viktor Horvath Date: Tue, 17 Dec 2024 16:57:01 +0100 Subject: [PATCH] EC2: Remove internal Network Interface traces from the Subnet after deletion. --- moto/ec2/models/elastic_network_interfaces.py | 2 ++ .../test_elastic_network_interfaces.py | 31 +++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/moto/ec2/models/elastic_network_interfaces.py b/moto/ec2/models/elastic_network_interfaces.py index 8b6b05437065..78b8e1e8e98b 100644 --- a/moto/ec2/models/elastic_network_interfaces.py +++ b/moto/ec2/models/elastic_network_interfaces.py @@ -204,6 +204,8 @@ def create_from_cloudformation_json( # type: ignore[misc] def delete(self) -> None: self.ec2_backend.delete_network_interface(eni_id=self.id) + for priv_ip in self.private_ip_addresses: + self.subnet.del_subnet_ip(priv_ip["PrivateIpAddress"]) def stop(self) -> None: if self.public_ip_auto_assign: diff --git a/tests/test_ec2/test_elastic_network_interfaces.py b/tests/test_ec2/test_elastic_network_interfaces.py index cd68efca399c..2980fbdcb7f3 100644 --- a/tests/test_ec2/test_elastic_network_interfaces.py +++ b/tests/test_ec2/test_elastic_network_interfaces.py @@ -1020,6 +1020,37 @@ def test_create_instance__termination_deletes_eni(delete_eni): ec2_client.delete_network_interface(NetworkInterfaceId=eni_id) +@mock_aws +def test_recreate_instance_with_same_ip_address(): + ssm = boto3.client("ssm", "us-east-1") + kernel_61 = "/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-6.1-x86_64" + ami_id = ssm.get_parameter(Name=kernel_61)["Parameter"]["Value"] + + ec2_client = boto3.client("ec2", "us-east-1") + existing_subnet_id = ec2_client.describe_subnets()["Subnets"][0]["SubnetId"] + + for _ in range(2): + # Second attempt must not throw an exception about a used IP + instance_id = ec2_client.run_instances( + MaxCount=1, + MinCount=1, + ImageId=ami_id, + InstanceType="t3a.small", + NetworkInterfaces=[ + { + "PrivateIpAddress": "172.31.0.5", + "DeleteOnTermination": True, + "DeviceIndex": 0, + "SubnetId": existing_subnet_id, + } + ], + )["Instances"][0]["InstanceId"] + ec2_client.get_waiter("instance_running").wait(InstanceIds=[instance_id]) + + ec2_client.terminate_instances(InstanceIds=[instance_id]) + ec2_client.get_waiter("instance_terminated").wait(InstanceIds=[instance_id]) + + def setup_vpc(boto3): # pylint: disable=W0621 ec2resource = boto3.resource("ec2", region_name="us-east-1") ec2client = boto3.client("ec2", "us-east-1")