104 lines
2.9 KiB
Python
104 lines
2.9 KiB
Python
#!/usr/bin/env python3
|
|
|
|
import os
|
|
import sys
|
|
import yaml
|
|
import subprocess
|
|
import json
|
|
import shutil
|
|
from datetime import datetime
|
|
import random
|
|
|
|
def load_config(config_file):
|
|
"""Load and parse YAML config file."""
|
|
with open(config_file, 'r') as f:
|
|
return yaml.safe_load(f)
|
|
|
|
def check_prerequisites():
|
|
"""Check if required tools are installed."""
|
|
required_tools = ['hcloud', 'jq']
|
|
for tool in required_tools:
|
|
if not shutil.which(tool):
|
|
print(f"Error: {tool} not found. Please install it first.")
|
|
sys.exit(1)
|
|
|
|
def check_hetzner_token():
|
|
"""Check if HCLOUD_TOKEN is set."""
|
|
if not os.environ.get('HCLOUD_TOKEN'):
|
|
print("Error: HCLOUD_TOKEN environment variable not set")
|
|
sys.exit(1)
|
|
|
|
def generate_hostname(config):
|
|
"""Generate a unique hostname."""
|
|
prefix = config['hostname']['prefix']
|
|
timestamp = datetime.now().strftime('%y%m%d')
|
|
random_num = random.randint(0, 999)
|
|
return f"{prefix}-{timestamp}-{random_num:03d}"
|
|
|
|
def get_image_id():
|
|
"""Get the base image ID."""
|
|
cmd = [
|
|
'hcloud', 'image', 'list',
|
|
'--type=snapshot',
|
|
'--selector=name=fedora-coreos-nullpoint',
|
|
'--output', 'json'
|
|
]
|
|
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
|
|
images = json.loads(result.stdout)
|
|
|
|
if not images:
|
|
print("Error: Base image not found. Run build.py first.")
|
|
sys.exit(1)
|
|
|
|
return images[0]['id']
|
|
|
|
def create_server(config, hostname, image_id):
|
|
"""Create a new server."""
|
|
hetzner = config['hetzner']
|
|
cmd = [
|
|
'hcloud', 'server', 'create',
|
|
'--name', hostname,
|
|
'--type', hetzner['server_type'],
|
|
'--datacenter', hetzner['datacenter'],
|
|
'--image', str(image_id),
|
|
'--ssh-key', hetzner['ssh_key_name'],
|
|
'--user-data-from-file', 'config.ign'
|
|
]
|
|
subprocess.run(cmd, check=True)
|
|
|
|
def get_server_ip(hostname):
|
|
"""Get the server's IP address."""
|
|
cmd = ['hcloud', 'server', 'ip', hostname]
|
|
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
|
|
return result.stdout.strip()
|
|
|
|
def main():
|
|
"""Main entry point."""
|
|
# Load config
|
|
if not os.path.exists('deploy-config.yaml'):
|
|
print("Error: deploy-config.yaml not found")
|
|
sys.exit(1)
|
|
|
|
config = load_config('deploy-config.yaml')
|
|
|
|
# Check prerequisites
|
|
check_prerequisites()
|
|
check_hetzner_token()
|
|
|
|
# Generate hostname
|
|
hostname = generate_hostname(config)
|
|
|
|
# Get image ID
|
|
image_id = get_image_id()
|
|
|
|
# Create server
|
|
print(f"Creating server '{hostname}'...")
|
|
create_server(config, hostname, image_id)
|
|
|
|
# Get server IP
|
|
server_ip = get_server_ip(hostname)
|
|
print(f"Server created! IP: {server_ip}")
|
|
print(f"You can connect using: ssh core@{server_ip}")
|
|
|
|
if __name__ == '__main__':
|
|
main() |