11# Copyright 2023 Canonical Ltd.
22# Licensed under the Apache V2, see LICENCE file for details.
33import logging
4+ import os
45import tempfile
56
67from kubernetes import client
@@ -29,21 +30,18 @@ def __init__(
2930 self .namespace = namespace
3031 self .remote_port = remote_port
3132 self .service = service
33+ self .temp_ca_file = None
34+ self .port_forwarder = None
3235
3336 try :
3437 self .remote_port = int (remote_port )
3538 except ValueError :
3639 raise ValueError (f"Invalid port number: { remote_port } " )
3740
38- self .port_forwarder = None
39-
4041 if ca_cert :
41- self .temp_ca_file = tempfile .NamedTemporaryFile () # noqa: SIM115
42- self .temp_ca_file .write (bytes (ca_cert , "utf-8" ))
43- self .temp_ca_file .flush ()
44- config .ssl_ca_cert = self .temp_ca_file .name
45- else :
46- self .temp_ca_file = None
42+ with tempfile .NamedTemporaryFile (delete = True ) as f :
43+ f .write (bytes (ca_cert , "utf-8" ))
44+ self .temp_ca_file = config .ssl_ca_cert = f .name
4745
4846 self .api_client = client .ApiClient (config )
4947
@@ -67,13 +65,16 @@ def connect(self):
6765
6866 def __del__ (self ):
6967 self .close ()
68+ try :
69+ if self .temp_ca_file :
70+ os .unlink (self .temp_ca_file )
71+ except FileNotFoundError :
72+ log .debug (f"file { self .temp_ca_file } not found" )
7073
7174 def close (self ):
7275 try :
7376 if self .port_forwarder :
7477 self .port_forwarder .close ()
75- if self .temp_ca_file :
76- self .temp_ca_file .close ()
7778 except AttributeError :
7879 pass
7980
0 commit comments