-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathgenerate_config.py
executable file
·88 lines (66 loc) · 2.73 KB
/
generate_config.py
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
#!/usr/bin/env python3
"""Generate configuration files for SimpleLogin Postfix and Certbot.
Greatly inspired by:
https://aoeex.com/phile/postfix-dovecot-and-lets-encrypt-certificates/
"""
import re
import sys
from os import environ
from pathlib import Path
from jinja2 import Environment, FileSystemLoader, StrictUndefined
from jinja2.exceptions import UndefinedError
# Certbot
CERTBOT_CONFIG_DIR = Path('/etc/letsencrypt')
CERTBOT_CONFIG_FILENAME = 'cli.ini'
# Let's Encrypt
LETSENCRYPT_CONFIG_DIR = CERTBOT_CONFIG_DIR / 'live'
LETSENCRYPT_CERTIFICATE = 'fullchain.pem'
LETSENCRYPT_PRIVATE_KEY = 'privkey.pem'
# Postfix
POSTFIX_CONFIG_DIR = Path('/etc/postfix')
POSTFIX_CONFIG_FILENAMES = ['main.cf', 'pgsql-relay-domains.cf', 'pgsql-transport-maps.cf'] # noqa: E501
# Templates
TEMPLATES_DIR = Path('/src/templates')
templates = Environment(
loader=FileSystemLoader(TEMPLATES_DIR),
undefined=StrictUndefined,
trim_blocks=True, # To not show empty lines in place of block statements
)
def generate_certbot_config():
"""Generate Certbot's configuration file."""
with (CERTBOT_CONFIG_DIR / CERTBOT_CONFIG_FILENAME).open('w') as f:
template = templates.get_template(f'certbot/{CERTBOT_CONFIG_FILENAME}')
f.write(template.render(env=environ))
def generate_postfix_config():
"""Generate Postfix's configuration files."""
for config in POSTFIX_CONFIG_FILENAMES:
with (POSTFIX_CONFIG_DIR / config).open('w') as f:
template = templates.get_template(f'postfix/{config}')
# Check if Certbot generated a TLS certificate.
postfix_fqdn = environ['POSTFIX_FQDN']
cert_file = LETSENCRYPT_CONFIG_DIR / postfix_fqdn / LETSENCRYPT_CERTIFICATE
key_file = LETSENCRYPT_CONFIG_DIR / postfix_fqdn / LETSENCRYPT_PRIVATE_KEY
enable_tls = cert_file.is_file() and key_file.is_file()
# Generate config file.
f.write(template.render(
env=environ,
tls=enable_tls,
tls_cert=cert_file,
tls_key=key_file,
))
def main():
"""Generate Certbot and/or Postfix's configuration files."""
try:
if '--certbot' in sys.argv or len(sys.argv) == 1:
generate_certbot_config()
if '--postfix' in sys.argv or len(sys.argv) == 1:
generate_postfix_config()
except (KeyError, UndefinedError) as exc:
if isinstance(exc, KeyError):
missing = exc.args[0]
else:
missing = re.match(r"'.+' .+ '(.+)'", exc.message)[1]
print("Impossible to generate Postfix configuration files")
sys.exit(f"You forgot to define the following environment variable: {missing}")
if __name__ == '__main__':
main()