80 lines
2.4 KiB
Python
80 lines
2.4 KiB
Python
#!/usr/bin/env python3
|
|
from pathlib import Path
|
|
|
|
from hcloud import Client
|
|
from hcloud.images.domain import Image
|
|
from hcloud.load_balancer_types.domain import LoadBalancerType
|
|
from hcloud.load_balancers.domain import LoadBalancerTarget, LoadBalancerService, LoadBalancerHealthCheck
|
|
from hcloud.locations.domain import Location
|
|
from hcloud.networks.domain import NetworkSubnet
|
|
from hcloud.server_types.domain import ServerType
|
|
|
|
with open('.credentials/token', 'r') as file:
|
|
client = Client(token=str(file.readline()).strip())
|
|
|
|
with open(f'{str(Path.home())}/.ssh/id_ed25519.pub', 'r') as file:
|
|
ssh_raw = file.readline()
|
|
|
|
index = 's444501'
|
|
ssh_name = index + '-ssh'
|
|
network_name = index + '-network'
|
|
server_base_name = index + '-server'
|
|
load_balancer_name = index + '-lb'
|
|
SERVER_COUNT = 5
|
|
|
|
ssh_key = client.ssh_keys.create(name=ssh_name, public_key=ssh_raw)
|
|
|
|
vnet = client.networks.create(
|
|
name=network_name,
|
|
ip_range="10.10.10.0/24",
|
|
subnets=[
|
|
NetworkSubnet(ip_range="10.10.10.0/24", network_zone="eu-central", type="cloud")
|
|
]
|
|
)
|
|
|
|
cloud_init = r'''#cloud-config
|
|
runcmd:
|
|
- git clone https://git.wmi.amu.edu.pl/s444501/chmury-loadbalancer.git
|
|
- cd chmury-loadbalancer
|
|
- chmod +x webservice
|
|
- ./webservice
|
|
'''
|
|
lb_targets = []
|
|
for i in range(SERVER_COUNT):
|
|
server = client.servers.create(
|
|
name=server_base_name + '-' + str(i+1),
|
|
server_type=ServerType("cx11"),
|
|
image=Image(name="ubuntu-22.04"),
|
|
ssh_keys=[ssh_key],
|
|
networks=[vnet],
|
|
location=Location("hel1"),
|
|
user_data=cloud_init
|
|
)
|
|
server.action.wait_until_finished()
|
|
print(f"Tworzenie serwera {i+1}: {server.action.complete}")
|
|
lb_targets.append(LoadBalancerTarget(type="server", server=server.server, use_private_ip=True))
|
|
|
|
|
|
lb = client.load_balancers.create(
|
|
name=load_balancer_name,
|
|
load_balancer_type=LoadBalancerType(name="lb11"),
|
|
location=Location("hel1"),
|
|
services=[
|
|
LoadBalancerService(
|
|
protocol="http",
|
|
listen_port=8080,
|
|
destination_port=8080,
|
|
proxyprotocol=False
|
|
)
|
|
],
|
|
targets=lb_targets,
|
|
public_interface=True,
|
|
network=vnet
|
|
)
|
|
|
|
lb.action.wait_until_finished()
|
|
print(f"Mechanizm równoważenia obciążenia został utworzony: {lb.action.complete}")
|
|
|
|
|
|
print(f"Webserwis pod adresem http://{lb.load_balancer.data_model.public_net.ipv4.ip}:8080/factors/")
|