-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcertbot.py
More file actions
198 lines (164 loc) · 5.35 KB
/
certbot.py
File metadata and controls
198 lines (164 loc) · 5.35 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# Save this in a file called certbot.json and edit as required
#
# {
# "domain": "example.com",
# "email": "certbot@example.com",
# "legacy_compose": false,
# "nginx_image": "nginx:latest",
# "volume_prefix": "./data"
# }
# Do not change anything below this line, unless you know what you are doing :)
import json
import os
DOCKER_COMPOSE_TEMPLATE = """version: '3'
services:
webserver:
image: [NGINX_IMAGE]
ports:
- 80:80
- 443:443
restart: always
volumes:
- [VOLUME_PREFIX]/certbot/conf/:/etc/nginx/ssl/:ro
- [VOLUME_PREFIX]/certbot/www:/var/www/certbot/:ro
- ./nginx.conf:/etc/nginx/conf.d/default.conf:ro
certbot:
image: certbot/certbot:latest
volumes:
- [VOLUME_PREFIX]/certbot/conf/:/etc/letsencrypt/:rw
- [VOLUME_PREFIX]/certbot/www/:/var/www/certbot/:rw"""
LETSENCRYPT_TEMPLATE = "[COMPOSE] run --rm certbot certonly --webroot --webroot-path /var/www/certbot/ [DRYRUN] -d [DOMAIN] --non-interactive --agree-tos -m [EMAIL]"
NGINX_PRE_TEMPLATE = """server {
listen 80 default_server;
listen [::]:80;
location /.well-known/acme-challenge/ {
root /var/www/certbot;
}
location / {
return 301 https://$host$request_uri;
}
}"""
NGINX_POST_TEMPLATE = """server {
listen 80;
listen [::]:80;
server_name _;
server_tokens off;
location /.well-known/acme-challenge/ {
root /var/www/certbot;
}
location / {
return 301 https://[DOMAIN]$request_uri;
}
}
server {
listen 443 default_server ssl http2;
listen [::]:443 ssl http2;
server_name _;
server_tokens off;
ssl_certificate /etc/nginx/ssl/live/[DOMAIN]/fullchain.pem;
ssl_certificate_key /etc/nginx/ssl/live/[DOMAIN]/privkey.pem;
location / {
if ( $host !~* ^([DOMAIN])$ ) {
return 444;
}
# you will likely want to replace the following line with
# your own configuration
root /usr/share/nginx/html;
}
}"""
class DockerNginxLetsEncryptSetup:
def __init__(self):
f = open("certbot.json")
self.config = json.load(f)
f.close()
# TODO: validate the config, e.g.
# - domain is a valid fqdn
# - legacy_compose exists
# - volume_prefix is a non-empty string
# - email is a valid email string
def cleanup(self):
print(
f"\n\nDone. Navigate to https://{self.config['domain']} in your browser..."
)
if input(
f"\nRemove the setup files (if {self.config['domain']} has a valid certificate you don't need them anymore) (Y/n): "
) in ["", "y", "Y"]:
os.remove("certbot.json")
os.remove("certbot.py")
print("Deleted the setup files.")
print(
"\nAdd the following lines to your crontab to auto-renew this certificate:"
)
print(f"0 0,12 * * * {self.compose(True)} run --rm certbot renew")
print(f"5 0,12 * * * docker exec webserver nginx -s reload")
print(
"\nEdit the docker-compose.yml and nginx.conf files to suit your project, being careful that you:"
)
print(" 1) don't remove any of the 'volumes' lines in docker-compose.yml")
print(" 2) don't remove any of the 'ssl_cert*' lines in nginx.conf")
def compose(self, include_path):
if self.config["legacy_compose"]:
return "/usr/local/bin/docker-compose" if include_path else "docker-compose"
return "docker compose"
def get_certificate(self, dry_run=True):
os.system(
LETSENCRYPT_TEMPLATE.replace(
"[COMPOSE]",
self.compose(False),
)
.replace(
"[DOMAIN]",
self.config["domain"],
)
.replace(
"[DRYRUN]",
"--dry-run" if dry_run else "",
)
.replace(
"[EMAIL]",
self.config["email"],
)
)
def setup(self):
self.stop_docker()
self.write_docker_compose_yml()
self.write_pre_nginx_conf()
self.start_docker()
self.get_certificate(dry_run=False)
self.stop_docker()
self.write_post_nginx_conf()
self.start_docker()
self.cleanup()
def start_docker(self):
os.system(f"{self.compose(False)} up -d")
def stop_docker(self):
if os.path.exists("docker-compose.yml"):
os.system(f"{self.compose(False)} down")
def write_docker_compose_yml(self):
self.write_file(
"docker-compose.yml",
DOCKER_COMPOSE_TEMPLATE.replace(
"[NGINX_IMAGE]",
self.config["nginx_image"],
).replace(
"[VOLUME_PREFIX]",
self.config["volume_prefix"],
),
)
def write_file(self, filename, contents):
f = open(filename, "w")
f.write(contents)
f.close()
def write_post_nginx_conf(self):
self.write_file(
"nginx.conf",
NGINX_POST_TEMPLATE.replace(
"[DOMAIN]",
self.config["domain"],
),
)
def write_pre_nginx_conf(self):
self.write_file("nginx.conf", NGINX_PRE_TEMPLATE)
if __name__ == "__main__":
dnles = DockerNginxLetsEncryptSetup()
dnles.setup()