nginx-configurator/n-ssl.py

93 lines
2.7 KiB
Python
Raw Normal View History

2023-10-26 12:36:19 +02:00
import os
import subprocess
import re
# NGINX_DIR="/etc/nginx"
# DOMAINS_TXT = "/etc/autossl/domains.txt"
# DEHYDRATED_LOC = "/etc/autossl/dehydrated.sh"
NGINX_DIR = "./nginx"
DOMAINS_TXT = "./autossl/domains.txt"
DEHYDRATED_LOC = "./autossl/dehydrated.sh"
REMOTE = "10.55.55.55" # make a .env variable or something like that. It will be different on each server
def create_domfile():
# Get nginx config files with "# AUTOSSL" tag, parse IDs and domains and create domains.txt file for Dehydrated
sites_path = NGINX_DIR + "/sites"
# It's probably not the best to use grep here, but it's really fast unlike reading files in Python directly. But what can go wrong? (lol)
grep_out = subprocess.run(
["grep", "-Rh", "AUTOSSL", sites_path], capture_output=True, text=True
)
if grep_out.returncode == 0:
DOMAIN_LINES = []
for line in grep_out.stdout.splitlines():
id = re.findall(r"\d+", line)[-1]
domains = re.findall(r"(?<=server_name )(.*)(?=;)", line)[0]
DOMAIN_LINES.append(domains + " > " + str(id))
if len(DOMAIN_LINES) > 0:
with open(DOMAINS_TXT, "w") as fp:
for line in DOMAIN_LINES:
# write each item on a new line
fp.write("%s\n" % line)
else:
print("No data to write to domains.txt. \n Aborting")
exit()
else:
print("Finding #AUTOSSL comments in nginx configs failed.")
exit()
def request_cert():
print("Requesting certificate")
dehydrated_run = subprocess.run(
[DEHYDRATED_LOC, "-c"], capture_output=True, text=True
)
if dehydrated_run.returncode != 0:
print("Something went wrong with dehydrated.sh")
print(dehydrated_run.stdout)
else:
print(
"Certificates are successfully dehydrated. (It went OK and cert is now generated)"
)
def reload_local_nginx():
nginx_check = subprocess.run(["nginx", "-t"], capture_output=True, text=True)
if nginx_check.returncode != 0:
print("nginx config is not valid! Aborting")
print(nginx_check.stdout)
exit()
nginx_reload = subprocess.run(
["systemctl", "reload", "nginx.service"], capture_output=True, text=True
)
if nginx_reload.returncode != 0:
print("Nginx reload returned non-zero status code")
print(nginx_reload.stdout)
exit()
def remote_replication(remote):
# Do RSYNC to second server
return True
def remote_reload(remote):
# Check and reload nginx on second server
return True
def main():
# create_domfile()
request_cert()
reload_local_nginx()
remote_replication(REMOTE)
remote_reload(REMOTE)
if __name__ == "__main__":
main()