Why Automate Server Setup?
Manual server configuration is error-prone and slow. Python scripts let you reproduce identical environments in seconds.
Installing Packages
python
import subprocess
import sys
PACKAGES = ["nginx", "postgresql", "redis-server", "fail2ban"]
def install_packages(packages: list[str]) -> None:
"""Install system packages via apt."""
subprocess.run(["apt-get", "update"], check=True)
for pkg in packages:
print(f"Installing {pkg}...")
subprocess.run(["apt-get", "install", "-y", pkg], check=True)
print(f"{pkg} installed")
if __name__ == "__main__":
install_packages(PACKAGES)
Configuring Nginx
Once installed, you can template your Nginx config:
python
from pathlib import Path
NGINX_TEMPLATE = """
server {{
listen 80;
server_name {domain};
location / {{
proxy_pass http://127.0.0.1:{port};
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}}
}}
"""
def create_nginx_config(domain: str, port: int) -> None:
config = NGINX_TEMPLATE.format(domain=domain, port=port)
path = Path(f"/etc/nginx/sites-available/{domain}")
path.write_text(config)
Path(f"/etc/nginx/sites-enabled/{domain}").symlink_to(path)
print(f"Nginx config created for {domain} -> port {port}")
Health Check Script
python
import requests
def check_health(urls: list[str]) -> dict[str, bool]:
results = {}
for url in urls:
try:
r = requests.get(url, timeout=5)
results[url] = r.status_code == 200
except requests.RequestException:
results[url] = False
return results
endpoints = [
"https://api.example.com/health",
"https://cdn.example.com/status",
]
for url, ok in check_health(endpoints).items():
status = "OK" if ok else "FAIL"
print(f"{status} {url}")
Next Steps
Combine these scripts into a single provisioning tool and integrate with Xitoring's API to auto-register new servers for monitoring.
