refactor(config): replace temp file usage with temp dir

Updated the saving mechanism for temporary configuration files by utilizing a temporary directory instead of a named temporary file. This change streamlines file handling and avoids potential issues related to file name collisions.

Improves reliability of configuration updates by ensuring a cleaner and more isolated temporary workspace, which enhances process safety and consistency.
This commit is contained in:
Kumi 2024-07-18 18:46:05 +02:00
parent b60efb3f96
commit c3c5f36ffc
Signed by: kumi
GPG key ID: ECBCC9082395383F

View file

@ -62,16 +62,19 @@ def main():
updated_content = replace_peer_section(config_content, new_peer_section)
# Step 4: Save the updated configuration file
with tempfile.NamedTemporaryFile(delete=False, mode='w') as temp_file:
temp_file.write(updated_content)
temp_file_path = temp_file.name
with tempfile.TemporaryDirectory(delete=False, mode='w') as tempdir:
temp_file = pathlib.Path(tempdir) / f"{interface}.conf"
temp_file_path = str(temp_file)
# Step 5: Apply the updated Wireguard configuration
subprocess.run(["wg-quick", "down", interface], stderr=subprocess.DEVNULL)
subprocess.run(["wg-quick", "up", temp_file_path])
with open(temp_file_path, 'w') as file:
file.write(updated_content)
# Overwrite the original config file with the updated content
os.replace(temp_file_path, config_path)
# Step 5: Apply the updated Wireguard configuration
subprocess.run(["wg-quick", "down", interface], stderr=subprocess.DEVNULL)
subprocess.run(["wg-quick", "up", temp_file_path])
# Overwrite the original config file with the updated content
os.replace(temp_file_path, config_path)
print(f"Local Wireguard configuration for {interface} updated and applied successfully.")