import os import sys from minio import Minio from urllib.request import urlopen from json import loads minio_client = Minio( "minio.sprinthub.ru:9000", access_key="serviceminioadmin", secret_key=os.getenv("MINIO_SECRET_KEY", "minioadmin"), secure=False, ) def get(url): with urlopen(url) as response: data = response.read().decode("utf-8") return loads(data) try: response = get( "http://configurator/api/v1/fetch?project=certupdater&stage=production" ) hosts = response["configs"]["hosts"] except Exception as e: print(f"Error fetching config: {e}", file=sys.stderr) sys.exit(1) config = "" for host, params in hosts.items(): config += """ server {{ listen 443 ssl http2; listen [::]:443 ssl http2; server_name {host}; ssl_certificate /etc/nginx/{host}/fullchain.pem; ssl_certificate_key /etc/nginx/{host}/privkey.pem; add_header X-Frame-Options "SAMEORIGIN" always; add_header X-XSS-Protection "1; mode=block" always; add_header X-Content-Type-Options "nosniff" always; add_header Referrer-Policy "no-refferer-when-downgrade" always; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; location / {{ resolver 127.0.0.11; proxy_pass http://{target_host}:{port}$request_uri; }} }}\n\n """.format( host=host, target_host=params["host"], port=params["port"] ) try: fullchain = minio_client.get_object( "certupdater", f"certificates/{host}/fullchain.pem" ) privkey = minio_client.get_object( "certupdater", f"certificates/{host}/privkey.pem" ) try: os.makedirs(f"/etc/nginx/{host}", exist_ok=True) except OSError as e: print(f"Error creating directory: {e}", file=sys.stderr) continue with open(f"/etc/nginx/{host}/fullchain.pem", "wb") as fp: fp.write(fullchain.data) with open(f"/etc/nginx/{host}/privkey.pem", "wb") as fp: fp.write(privkey.data) except Exception as e: print(f"Error processing host {host}: {e}", file=sys.stderr) continue try: with open("/etc/nginx/hosts.conf", "w") as fp: fp.write(config) except Exception as e: print(f"Error writing config file: {e}", file=sys.stderr) sys.exit(1)