infra/roles/certbot/templates/letsencrypt-hook.py.j2

48 lines
1.3 KiB
Django/Jinja

#!/usr/bin/env python3
import os
import shutil
import sys
import matrixmsg
filenames = ["cert.pem", "chain.pem", "fullchain.pem", "privkey.pem"]
letsencrypt_live = "/etc/letsencrypt/live"
cert_repo = "/usr/local/etc/letsencrypt/live"
def renewed_cert(name):
src_dir = os.path.join(letsencrypt_live, name)
dest_dir = os.path.join(cert_repo, name)
os.makedirs(dest_dir, exist_ok=True)
try:
for fname in filenames:
src = os.path.join(src_dir, fname)
dest = os.path.join(dest_dir, fname)
shutil.copy(src, dest)
privkey = os.path.join(dest_dir, 'privkey.pem')
os.chmod(privkey, 0o640)
shutil.chown(privkey, group="adm")
matrix_status_code = matrixmsg.send(f"cert: `{name}`")
if matrix_status_code not in [200, 201]:
print(f"matrixmsg error: {matrix_status_code}")
print(f"renewed: {name}")
except FileNotFoundError:
matrixmsg.send(f"no files found for `{name}` in `RENEWED_DOMAINS`")
def main():
try:
for name in os.environ['RENEWED_DOMAINS'].split(" "):
if name.startswith("*."):
name = ".".join(name.split(".")[1:])
renewed_cert(name)
except KeyError:
print("error: no 'RENEWED_DOMAINS' env var present!")
if __name__ == "__main__":
sys.exit(main())