DPZC-03_IaaS/deploy.py

76 lines
2.9 KiB
Python
Raw Normal View History

2021-11-28 19:15:37 +01:00
import json
from hcloud import Client
2021-11-28 19:42:50 +01:00
from hcloud.networks.domain import NetworkSubnet
from hcloud.locations.domain import Location
2021-11-28 19:59:11 +01:00
from hcloud.images.domain import Image
from hcloud.server_types.domain import ServerType
2021-11-28 19:15:37 +01:00
class Client_MS:
def __init__(self) -> None:
2021-11-28 19:59:11 +01:00
with open("db.yml", "r") as f:
self.db_yml = f.read()
2021-11-28 19:15:37 +01:00
self.config = self.load_config()
self.client = Client(token=self.config["token"])
2021-11-28 19:42:50 +01:00
self.ssh_key = self.get_ssh()
self.network = self.create_network()
self.volume = self.create_volume()
2021-11-28 19:59:11 +01:00
self.server_db = self.create_db_server()
2021-11-28 19:15:37 +01:00
def load_config(self):
with open('config.json') as json_file:
return json.load(json_file)
2021-11-28 19:42:50 +01:00
def get_ssh(self):
if(self.client.ssh_keys.get_by_name(self.config["ssh_name"])):
print("SSH_KEY: Key exists.")
return self.client.ssh_keys.get_by_name(self.config["ssh_name"])
else:
print("SSH_KEY: Creating ssh_key.")
return self.client.ssh_keys.create(name=self.config["ssh_name"], public_key=self.config["ssh_public"])
def create_network(self):
if(self.client.networks.get_by_name(self.config["network"])):
print("NETWORK: Network exists.")
return self.client.networks.get_by_name(self.config["network"])
else:
print("NETWORK: Creating network.")
return self.client.networks.create(
name=self.config["network"],
ip_range=self.config["network-ip"],
subnets=[
NetworkSubnet(ip_range=self.config["network-ip"],
network_zone="eu-central", type="cloud")
]
)
def create_volume(self):
if(self.client.volumes.get_by_name(self.config["volume"])):
print("VOLUME: Volume exists.")
return self.client.volumes.get_by_name(self.config["volume"])
else:
print("VOLUME: Creating volume.")
return self.client.volumes.create(
2021-11-28 19:59:11 +01:00
size=10, name=self.config["volume"], location=Location(id=self.config["location"]))
def create_db_server(self):
if(self.client.servers.get_by_name(self.config["db-server-name"])):
print("DB: Server exists.")
return self.client.servers.get_by_name(self.config["db-server-name"])
else:
print("DB: Creating server.")
return self.client.servers.create(
name=self.config["db-server-name"],
server_type=ServerType(self.config["server-type"]),
image=Image(name=self.config["server-image"]),
ssh_keys=[self.ssh_key],
networks=[self.network],
location=Location(self.config["location"]),
user_data=self.db_yml)
2021-11-28 19:42:50 +01:00
2021-11-28 19:15:37 +01:00
c = Client_MS()
print(c.client)
2021-11-28 19:42:50 +01:00
print(c.ssh_key)