pzc-hetzner/zadanie_4.py
Andrzej Preibisz 478035c6e3 Hetzner
2023-01-15 17:10:30 +01:00

66 lines
1.6 KiB
Python

from hcloud import Client
from hcloud.locations.domain import Location
from hcloud.images.domain import Image
from hcloud.server_types.domain import ServerType
from hcloud.networks.domain import NetworkSubnet
api_token = ""
with open("token.txt", "r") as file:
api_token = file.read().strip()
client = Client(token=api_token)
PREFIX = "444465"
YOUR_LOCAL_SSH_PUBKEY = ""
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=vnet_name,
ip_range="10.0.0.0/16",
subnets=[
NetworkSubnet(ip_range="10.0.0.0/16", network_zone="eu-central", type="cloud")
]
)
ssh_name = f"{PREFIX}-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=ssh_name, public_key=YOUR_LOCAL_SSH_PUBKEY)
cloud_init=r'''#cloud-config
packages:
- apt-transport-https
- ca-certificates
- curl
- gnupg-agent
- software-properties-common
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}-code-server",
server_type=ServerType("cx11"),
image=Image(name="ubuntu-20.04"),
ssh_keys=[ssh_key],
networks=[vnet],
location=Location("hel1"),
user_data=cloud_init
)
vscode_server.action.wait_until_finished()
print(f"VSCode server created: {vscode_server.action.complete}")