57 lines
1.3 KiB
Python
57 lines
1.3 KiB
Python
import argparse
|
|
import logging
|
|
import sys
|
|
from datetime import datetime
|
|
from datetime import timezone
|
|
|
|
import tomli
|
|
from hcloud import Client
|
|
|
|
|
|
def setup_arguments():
|
|
parser = argparse.ArgumentParser()
|
|
|
|
parser.add_argument(
|
|
"-c",
|
|
"--config",
|
|
required=True,
|
|
help="Path to config file",
|
|
)
|
|
|
|
return parser
|
|
|
|
|
|
def main():
|
|
parser = setup_arguments()
|
|
args = parser.parse_args()
|
|
|
|
with open(args.config, "rb") as config_file:
|
|
try:
|
|
config = tomli.load(config_file)
|
|
except ValueError:
|
|
logging.critical("Invalid toml in config file.")
|
|
sys.exit()
|
|
|
|
logging.basicConfig(
|
|
format="%(asctime)s - %(message)s", level=config["loglevel"].upper()
|
|
)
|
|
|
|
client = Client(token=config["api_token"])
|
|
|
|
hcloud_servers = client.servers.get_all()
|
|
|
|
if len(hcloud_servers) == 0:
|
|
logging.info("No servers exist, exiting...")
|
|
sys.exit
|
|
|
|
for server in hcloud_servers:
|
|
time_diff = datetime.now(timezone.utc) - server.created
|
|
|
|
if time_diff.days > 0 or time_diff.seconds > config["threshold"]:
|
|
delete_server(client, server)
|
|
|
|
|
|
def delete_server(client, server):
|
|
logging.warning("Server has existed longer than the allowed threshold, deleting...")
|
|
client.servers.delete(server)
|