Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

EC2: Remove internal Network Interface traces from the Subnet after deletion #8415

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading