dpzc-hetzner/cloud-init.py

70 lines
2.1 KiB
Python
Raw Normal View History

2022-12-31 11:52:43 +01:00
from hcloud import Client
from hcloud.images.domain import Image
from hcloud.server_types.domain import ServerType
from hcloud.networks.domain import NetworkSubnet
from hcloud.locations.domain import Location
from pathlib import Path
with open(f'{str(Path.home())}/.ssh/id_ed25519.pub', 'r') as file:
ssh_pub = file.readline()
with open("token.txt", "r") as file:
api_token = file.read().strip()
client = Client(token=api_token)
PREFIX = "s478839"
ssh_name = f"{PREFIX}-pzc-ssh-key"
ssh_key = client.ssh_keys.get_by_name(ssh_name) or None
if not ssh_key:
ssh_key = client.ssh_keys.create(name=f"{PREFIX}-pzc-ssh-key", public_key=ssh_pub)
print(f"Klucz {ssh_key.data_model.name} został dodany: {ssh_key.data_model.public_key}")
vnet_name = f"{PREFIX}-pzc-test-vnet"
vnet = client.networks.get_by_name(vnet_name) or None
if not vnet:
vnet = client.networks.create(
name=f"{PREFIX}-pzc-test-vnet",
ip_range="10.10.10.0/24",
subnets=[
NetworkSubnet(ip_range="10.10.10.0/24", network_zone="eu-central", type="cloud")
]
)
print(f"Utworzono sieć wirtualną {vnet.data_model.name} ({vnet.data_model.ip_range})")
cloud_init_vscode=r'''#cloud-config
write_files:
- content: |
curl -fsSL https://code-server.dev/install.sh > /root/install.sh
path: /root/install.sh
owner: root:root
permissions: '755'
runcmd:
- bash /root/install.sh
- code-server --bind-addr 0.0.0.0:8080
'''
vscode_server = client.servers.create(
name=f"{PREFIX}-vscode",
server_type=ServerType("cx11"),
image=Image(name="ubuntu-20.04"),
ssh_keys=[ssh_key],
networks=[vnet],
location=Location("hel1"),
user_data=cloud_init_vscode)
vscode_server.action.wait_until_finished()
print(f"Tworzenie serwera vscode: {vscode_server.action.complete}")
vscode_server = client.servers.get_by_name(f"{PREFIX}-vscode")
print(f"Serwer: {vscode_server.data_model.name}\n\tpubliczne IP: {vscode_server.data_model.public_net.ipv4.ip}\n\tprywatne IP: {vscode_server.data_model.private_net[0].ip}")
print(f"http://{vscode_server.data_model.public_net.ipv4.ip}:8080")