IaaS-gitea/cloud.ipynb
2024-12-09 20:21:07 +01:00

12 KiB

LAB2 - s444820 - Krystian Osiński


1. define constants and client:

#Config
TOKEN = "ZPN0YNl3TpYGe1xfxvFzV4zPOBVIEZTunC8Cg26JI1MEA9cso6O5Ydrin2wQnGxh"
PREFIX = "s444820"
SSH_PUBKEY = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDUSprPwtOEBCrPdf3pDhtwpWN2SNxemlrXvglqqL+kKGjnfP3RO7CIcjw7etQDC+2FIWaiqToWPSAKrxi4w235gPlT8GPvoKb1Wwv4BRMWiIr20bTiASorojzCQOlgb5ZShZH/opsWQ5geP9M26mkpNF5Ev/OMIKzfS6d6RHs1ZyX+81wfDhK2oxe4kAHTU8oQB/C7dGpeT4GohnG/SIj7ChoT10+Vkr0h+/yL9gVJUdnELacA29wBR+qhfzAP7YrSPwEtaFZxQ1rwOpJ39niljKfqPIxqA0ZOsNZnkCuTUMwMnQRFyO21x8nDzJe/WG95ptXiN4huPZVo0WQK7bfz5od8IY50Rm0XtCyjG0cVu0HSdJJzMgpluu4YQRvvs3xnwvknuT1G8prydJCDzNJ1nN8gnIEd4EymUPCoLRsc0s1fBvkX+t11cqnVvvTlCsBFzKYFzsKpSWRfFrwAfog6nOPb/3kAW8nj5QJinEByDkj9BtR2bCmLwp9DjlRokvDbijVVdEd8Ia5yyri9R9RRufmzmI5epe4PHCfzG6n3Wl4kj9+YHWDrg10x2IZo1zdzDKbH2cNqzS5c8HD2yjrVy7UkOKZTwlL/CHwIGqBQ9pMS0qgNpBJG/C6Y7MVQJEgP63IgtxSWuhGXwKbTuQnz0ROxlbrjdeMPVxH+6O0iDQ== kryosi@st.amu.edu.pl"
from hcloud import Client
client = Client(
    token=TOKEN
)

2. Add ssh key

ssh_key = client.ssh_keys.create(name=f"{PREFIX}-ssh-key", public_key=SSH_PUBKEY)
print(f"Klucz {ssh_key.data_model.name} został dodany: {ssh_key.data_model.public_key}")
Klucz s444820-ssh-key został dodany: ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDUSprPwtOEBCrPdf3pDhtwpWN2SNxemlrXvglqqL+kKGjnfP3RO7CIcjw7etQDC+2FIWaiqToWPSAKrxi4w235gPlT8GPvoKb1Wwv4BRMWiIr20bTiASorojzCQOlgb5ZShZH/opsWQ5geP9M26mkpNF5Ev/OMIKzfS6d6RHs1ZyX+81wfDhK2oxe4kAHTU8oQB/C7dGpeT4GohnG/SIj7ChoT10+Vkr0h+/yL9gVJUdnELacA29wBR+qhfzAP7YrSPwEtaFZxQ1rwOpJ39niljKfqPIxqA0ZOsNZnkCuTUMwMnQRFyO21x8nDzJe/WG95ptXiN4huPZVo0WQK7bfz5od8IY50Rm0XtCyjG0cVu0HSdJJzMgpluu4YQRvvs3xnwvknuT1G8prydJCDzNJ1nN8gnIEd4EymUPCoLRsc0s1fBvkX+t11cqnVvvTlCsBFzKYFzsKpSWRfFrwAfog6nOPb/3kAW8nj5QJinEByDkj9BtR2bCmLwp9DjlRokvDbijVVdEd8Ia5yyri9R9RRufmzmI5epe4PHCfzG6n3Wl4kj9+YHWDrg10x2IZo1zdzDKbH2cNqzS5c8HD2yjrVy7UkOKZTwlL/CHwIGqBQ9pMS0qgNpBJG/C6Y7MVQJEgP63IgtxSWuhGXwKbTuQnz0ROxlbrjdeMPVxH+6O0iDQ== kryosi@st.amu.edu.pl

3. Create vNet

from hcloud.networks.domain import NetworkSubnet

vnet = client.networks.create(
    name=f"{PREFIX}-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})")
Utworzono sieć wirtualną s444820-vnet (10.10.10.0/24)

4. Create DB VPS (PostgreSQL)

cloud_init_db=f'''#cloud-config

write_files:
  - path: /root/docker-compose.yml
    content: |
        version: '3.9'

        services:
          db:
              image: postgres:14
              restart: always
              ports:
                - "10.10.10.2:5432:5432"
              environment:
                - POSTGRES_USER=gitea
                - POSTGRES_PASSWORD=gitea
                - POSTGRES_DB=gitea
              volumes:
                - ./DB:/var/lib/postgresql/data

runcmd:
  - apt update
  - apt install -y docker.io docker-compose
  - docker-compose -f /root/docker-compose.yml up -d
'''
from hcloud.images.domain import Image
from hcloud.server_types.domain import ServerType
from hcloud.locations import Location

db_server = client.servers.create(
    name=f"{PREFIX}-DB", server_type=ServerType("cx22"), image=Image(name="ubuntu-24.04"),location=Location("hel1"),ssh_keys=[ssh_key],networks=[vnet],user_data=cloud_init_db 
)

db_server.action.wait_until_finished()
print(f"Utworzono serwer: {db_server.server.data_model.name} ({db_server.server.data_model.public_net.ipv4.ip}) {db_server.server.data_model.private_net[0].ip}")
Utworzono serwer: s444820-DB (37.27.197.45) 10.10.10.2

5. Create volume:

from hcloud.volumes.domain import Volume

volume = client.volumes.create(
    name=f"{PREFIX}-volume",size=10,location=Location("hel1")
)

print(f"Utworzono wolumen: {volume.volume.data_model.name} ({volume.volume.data_model.size} GB)")
Utworzono wolumen: s444820-volume (10 GB)

6. Create Gitea VPS

cloud_init_gitea=f'''#cloud-config

write_files:
  - path: /root/docker-compose.yml
    content: |
        version: "3"
        services:
          server:
            image: gitea/gitea:1.14.5-rootless
            environment:
              - GITEA__database__DB_TYPE=postgres
              - GITEA__database__HOST={db_server.server.data_model.private_net[0].ip}
              - GITEA__database__NAME=gitea
              - GITEA__database__USER=gitea
              - GITEA__database__PASSWD=gitea
            restart: always
            volumes:
              - /mnt/HC_Volume_101746670/data:/var/lib/gitea
              - /mnt/HC_Volume_101746670/config:/etc/gitea
            ports:
              - "3000:3000"
              - "2222:2222"

runcmd:
  - apt update
  - apt install -y docker.io docker-compose
  - mkdir -p /mnt/HC_Volume_101746670/data
  - mkdir -p /mnt/HC_Volume_101746670/config
  - sudo chmod -R 777 /mnt/HC_Volume_101746670/data
  - sudo chmod -R 777 /mnt/HC_Volume_101746670/config
  - docker-compose -f /root/docker-compose.yml up -d
'''
from hcloud.locations.domain import Location

gitea_server = client.servers.create(
    name=f"{PREFIX}-gitea-server", 
    server_type=ServerType("cx22"), 
    image=Image(name="ubuntu-24.04"), 
    ssh_keys=[ssh_key], 
    networks=[vnet], 
    location=Location("hel1"), 
    volumes=[volume.volume],
    user_data=cloud_init_gitea
)

gitea_server.action.wait_until_finished()
print(f"Tworzenie serwera db: {gitea_server.action.complete}")
Tworzenie serwera db: True

7. Task verification: (Wait a moment)

import webbrowser

gitea_url = f"http://{gitea_server.server.data_model.public_net.ipv4.ip}:3000"
print(f"Otwórz stronę w przeglądarce: {gitea_url}")
webbrowser.open(gitea_url)
Otwórz stronę w przeglądarce: http://65.21.53.29:3000
True

8. Resource release:

servers = client.servers.get_all()
print(f"Usuwanie {len(servers)} serwerów")
for s in servers:
    if s.data_model.name.startswith(PREFIX):
        action = client.servers.delete(s)
        print(f"\tUsuwanie serwera {s.data_model.name} ({s.data_model.public_net.ipv4.ip}): {action.data_model.status}")
        action.wait_until_finished()


ssh_keys = client.ssh_keys.get_all()
print(f"Usuwanie {len(ssh_keys)} kluczy SSH")
for s in ssh_keys:
    if s.data_model.name.startswith(PREFIX):
        action = client.ssh_keys.delete(s)
        print(f"\tUsuwanie klucza {s.name}: {action}")

vnets = client.networks.get_all()
print(f"Usuwanie {len(vnets)} sieci wirtualnych")
for s in vnets:
    if s.data_model.name.startswith(PREFIX):
        action = client.networks.delete(s)
        print(f"\tUsuwanie sieci wirtualnej {s.name}: {action}")

volumes = client.volumes.get_all()
print(f"Usuwanie {len(volumes)} wolumenów")
for v in volumes:
    if s.data_model.name.startswith(PREFIX):
        action = client.volumes.delete(v)
        print(f"\tUsuwanie wolumenu {v.name}: {action}")
Usuwanie 2 serwerów
	Usuwanie serwera s444820-DB (37.27.197.45): running
	Usuwanie serwera s444820-gitea-server (65.21.53.29): running
Usuwanie 1 kluczy SSH
	Usuwanie klucza s444820-ssh-key: True
Usuwanie 1 sieci wirtualnych
	Usuwanie sieci wirtualnej s444820-vnet: True
Usuwanie 1 wolumenów
	Usuwanie wolumenu s444820-volume: True