Skip to content

Commit 97a82b9

Browse files
authored
add a step to clean up unused network interfaces in the precreated subnets (#277)
1 parent 037d17a commit 97a82b9

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

integration/conftest.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import time
12
import boto3
23
import botocore
34
import pytest
@@ -63,6 +64,26 @@ def clean_all_integ_buckets():
6364
clean_bucket(bucket.name, s3_client)
6465

6566

67+
def _delete_unused_network_interface_by_subnet(ec2_client, subnet_id):
68+
"""Deletes unused network interface under the provided subnet"""
69+
paginator = ec2_client.get_paginator("describe_network_interfaces")
70+
response_iterator = paginator.paginate(
71+
Filters=[
72+
{"Name": "subnet-id", "Values": [subnet_id]},
73+
{"Name": "status", "Values": ["available"]},
74+
]
75+
)
76+
network_interface_ids = []
77+
for page in response_iterator:
78+
network_interface_ids += [ni["NetworkInterfaceId"] for ni in page["NetworkInterfaces"]]
79+
80+
for ni_id in network_interface_ids:
81+
ec2_client.delete_network_interface(NetworkInterfaceId=ni_id)
82+
time.sleep(0.5)
83+
84+
LOG.info("Deleted %s unused network interfaces under subnet %s", len(network_interface_ids), subnet_id)
85+
86+
6687
@pytest.fixture()
6788
def setup_companion_stack_once(tmpdir_factory, get_prefix):
6889
tests_integ_dir = Path(__file__).resolve().parents[1]
@@ -74,6 +95,15 @@ def setup_companion_stack_once(tmpdir_factory, get_prefix):
7495
companion_stack = Stack(stack_name, companion_stack_tempalte_path, cfn_client, output_dir)
7596
companion_stack.create_or_update(_stack_exists(stack_name))
7697

98+
ec2_client = ClientProvider().ec2_client
99+
precreated_subnet_ids = [
100+
resource["PhysicalResourceId"]
101+
for resource in companion_stack.stack_resources["StackResourceSummaries"]
102+
if resource["LogicalResourceId"].startswith("PreCreatedSubnet")
103+
]
104+
for subnet_id in precreated_subnet_ids:
105+
_delete_unused_network_interface_by_subnet(ec2_client, subnet_id)
106+
77107

78108
@pytest.fixture()
79109
def get_serverless_application_repository_app():

integration/helpers/client_provider.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ def __init__(self):
2525
self._kafka_client = None
2626
self._code_deploy_client = None
2727
self._sar_client = None
28+
self._ec2_client = None
2829

2930
@property
3031
def cfn_client(self):
@@ -216,3 +217,13 @@ def sar_client(self):
216217
if not self._sar_client:
217218
self._sar_client = boto3.client("serverlessrepo")
218219
return self._sar_client
220+
221+
@property
222+
def ec2_client(self):
223+
"""
224+
EC2 Client
225+
"""
226+
with self._lock:
227+
if not self._ec2_client:
228+
self._ec2_client = boto3.client("ec2")
229+
return self._ec2_client

0 commit comments

Comments
 (0)