"""Run with sudo on bastion after upload. Backup, validate, reload, rollback on failure.""" from pathlib import Path import subprocess,sys,uuid,shutil source=Path(sys.argv[1]) config=Path('/etc/nginx/conf.d/enne2.conf') snippet=Path('/etc/nginx/snippets/zombie-fps.conf') backup=Path('/etc/nginx/zombie-fps-backup-'+uuid.uuid4().hex[:12]) backup.mkdir(mode=0o700) shutil.copy2(config,backup/'enne2.conf') had_snippet=snippet.exists() if had_snippet: shutil.copy2(snippet,backup/'zombie-fps.conf') old=config.read_text() include=' include /etc/nginx/snippets/zombie-fps.conf;\n' anchor=' location /pub/ {' assert old.count(anchor)==1 new=old if include in old else old.replace(anchor,include+'\n'+anchor,1) shutil.copyfile(source,snippet) snippet.chmod(0o644) config.write_text(new) try: subprocess.run(['/usr/sbin/nginx','-t'],check=True) subprocess.run(['systemctl','reload','nginx'],check=True) except Exception: shutil.copy2(backup/'enne2.conf',config) if had_snippet: shutil.copy2(backup/'zombie-fps.conf',snippet) else: snippet.unlink(missing_ok=True) subprocess.run(['/usr/sbin/nginx','-t'],check=True) subprocess.run(['systemctl','reload','nginx'],check=True) raise print('Nginx validated and reloaded; protected backup:',backup)