-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdelete.py
More file actions
95 lines (77 loc) · 2.78 KB
/
Copy pathdelete.py
File metadata and controls
95 lines (77 loc) · 2.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import os
import subprocess
import docker
from pathlib import Path
import argparse
import re
import fcntl
client = docker.from_env()
nginx_container_name = "nginx"
conf_dir = Path("/home/dockeruser/nginx-https/nginx/conf.d")
conf_dir.mkdir(parents=True, exist_ok=True)
config_file = str(conf_dir / "auto_config.conf")
parser = argparse.ArgumentParser()
parser.add_argument("port", help="Port exposed by the container ")
parser.add_argument("subdomain", help="Subdomain to access the service")
parser.add_argument("manager_ip", help="IP of the manager server")
parser.add_argument("domain", help="Domain name")
parser.add_argument(
"domain", nargs="?", default="saggitarius.world", help="Domain name"
)
args = parser.parse_args()
domain_suffix = (
".localtest.me" if os.getenv("ENVIRONMENT") == "development" else args.domain
)
if not domain_suffix.startswith("."):
domain_suffix = "." + domain_suffix
def delete_nginx_config(
subdomain: str, port: str, manager_ip: str, domain: str = "saggitarius.world"
):
fqdn = f"{subdomain}{domain_suffix}"
if not os.path.exists(config_file):
print(f"No configuration file found at {config_file}")
return
config_block = f"""
server {{
server_name {subdomain}.{domain};
listen 443 ssl;
ssl_certificate /etc/letsencrypt/live/{subdomain}.{domain}/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/{subdomain}.{domain}/privkey.pem;
location ^~ /.well-known/acme-challenge/ {{
root /var/www/certbot;
try_files $uri =404;
}}
location / {{
resolver 127.0.0.11 valid=24000s;
set $upstream "{subdomain}_service:{port}";
proxy_pass http://{subdomain}_service:{port};
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;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}}
}}
"""
with open(config_file, "r+") as f: # r+ = read/write, no truncate
fcntl.flock(f, fcntl.LOCK_EX) # lock before reading
content = f.read()
new_content = content.replace(config_block, "")
# Go back to start and overwrite
f.seek(0)
f.truncate()
f.write(new_content)
f.flush()
fcntl.flock(f, fcntl.LOCK_UN) # release lock
def startop():
port = args.port
subdomain = args.subdomain
manager_ip = args.manager_ip
domain = args.domain
delete_nginx_config(
subdomain=subdomain, port=port, manager_ip=manager_ip, domain=domain
)
if __name__ == "__main__":
startop()