Skip to content

Commit

Permalink
EC2: Remove internal Network Interface traces from the Subnet after d…
Browse files Browse the repository at this point in the history
…eletion. (#8415)
  • Loading branch information
wandhydrant authored Dec 18, 2024
1 parent 3c4c72e commit f2e43c6
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
2 changes: 2 additions & 0 deletions moto/ec2/models/elastic_network_interfaces.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
31 changes: 31 additions & 0 deletions tests/test_ec2/test_elastic_network_interfaces.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down

0 comments on commit f2e43c6

Please sign in to comment.