DPZC-Hetzner/code-server/create_code_server.py
2022-12-30 03:22:03 +01:00

193 lines
5.7 KiB
Python
Executable File

#!/bin/python3
from hcloud import Client, APIException
from hcloud.images.domain import Image
from hcloud.networks.domain import NetworkSubnet
from hcloud.server_types.domain import ServerType
from hcloud.locations.domain import Location
from pathlib import Path
import sys
specific_name = "s478841"
key_name = f"ssh-{specific_name}"
net_name = f"code-net-{specific_name}"
volume_name = f"code-volume-{specific_name}"
server_name = f"code-server-{specific_name}"
location = Location("hel1")
CONFIG = r"""#cloud-config
packages:
- apt-transport-https
- ca-certificates
- curl
- gnupg-agent
- software-properties-common
write_files:
- path: /root/docker-compose.yml
content: |
version: "2.1"
services:
code-server:
image: lscr.io/linuxserver/code-server:latest
container_name: code-server
environment:
- PUID=1000
- PGID=1000
- TZ=Europe/London
volumes:
- /path/to/appdata/config:/config
ports:
- 8443:8443
restart: unless-stopped
runcmd:
- curl -fsSL https://download.docker.com/linux/ubuntu/gpg | apt-key add -
- add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
- apt-get update -y
- apt-get install -y docker-ce docker-ce-cli containerd.io
- curl -L "https://github.com/docker/compose/releases/download/1.29.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
- chmod +x /usr/local/bin/docker-compose
- systemctl start docker
- systemctl enable docker
- cd /root/ && docker-compose up -d
"""
def create_client(creds_path):
with open(creds_path, "r") as f:
token = str(f.readline()).strip()
client = Client(token=token)
print("The CLIENT has been CREATED")
return client
def load_key(key_folder, pub_key_name):
home_path = Path.home().joinpath(key_folder, pub_key_name)
print(f"\t\tUsing the {home_path} file")
with open(home_path) as f:
key = f.readline()
print("\t\tThe SSH KEY has been LOADED")
return key
def create_key(client, key_name, key_folder, pub_key_name):
print("The SSH KEY has been...")
key_of_power = load_key(key_folder, pub_key_name)
key = client.ssh_keys.create(name=key_name, public_key=key_of_power)
print("\tCREATED")
return key
def remove_key(client, key_name):
print("The KEY has been...", end="")
try:
action = client.ssh_keys.delete(client.ssh_keys.get_by_name(key_name))
action.wait_until_finished()
except AttributeError:
pass
print("DELETED")
def create_network(client, net_name, ip_range):
print("The NETWORK has been...", end="")
net = client.networks.create(
name=net_name,
ip_range=ip_range,
subnets=[
NetworkSubnet(ip_range=ip_range, network_zone="eu-central", type="cloud")
],
)
print("CREATED")
return net
def remove_network(client, net_name):
print("The NETWORK has been...", end="")
try:
action = client.networks.delete(client.networks.get_by_name(net_name))
action.wait_until_finished()
except AttributeError:
pass
print("DELETED")
def create_volume(client, volume_name, location):
print("The VOLUME has been...", end="")
volume = client.volumes.create(
name=volume_name, size=10, format="ext4", location=location
)
print("CREATED")
return volume
def remove_volume(client, volume_name):
print("The VOLUME has been...", end="")
try:
volume = client.volumes.get_by_name(volume_name)
try:
action = client.volumes.detach(volume)
action.wait_until_finished()
except APIException:
pass
action = client.volumes.delete(volume)
action.wait_until_finished()
except AttributeError:
pass
print("DELETED")
def create_code_server(client, server_name, ssh_key, vnet, volume, location, user_data):
print("The CODE SERVER has been CREATED:", end=" ")
code_server = client.servers.create(
name=server_name,
server_type=ServerType("cx11"),
image=Image(name="ubuntu-22.04"),
ssh_keys=[ssh_key],
networks=[vnet],
volumes=[volume.volume],
automount=True,
location=location,
user_data=user_data,
)
code_server.action.wait_until_finished()
print(code_server.action.complete)
return code_server
def remove_code_server(client, server_name):
print("The CODE SERVER has been...", end="")
try:
action = client.servers.delete(client.servers.get_by_name(server_name))
action.wait_until_finished()
except AttributeError:
pass
print("DELETED")
if __name__ == "__main__":
client = create_client("../tokens/token_file")
action = sys.argv[-1]
if action == "--create":
ssh_key = create_key(client, key_name, ".ssh", "id_ed25519.pub")
vnet = create_network(client, net_name, "10.10.10.0/24")
volume = create_volume(client, volume_name, location)
# Create a code server using loaded credentials and created resources
server = create_code_server(
client, server_name, ssh_key, vnet, volume, location, CONFIG
)
print(
f"You can access the server (in a few minutes) under the address: http://localhost:8888"
)
print("\n\n\t\tHave fun!")
elif action == "--clean":
remove_code_server(client, server_name)
remove_network(client, net_name)
remove_volume(client, volume_name)
remove_key(client, key_name)
print("\n\n\t\tIt was nice to meet you!")
else:
print(f"\nSorry, don't know what the'{action}' means...bye!")