|
| 1 | +from pyinfra.operations import files, server, systemd |
| 2 | + |
| 3 | +from cmdeploy.basedeploy import Deployer, get_resource |
| 4 | + |
| 5 | + |
| 6 | +class ExternalTlsDeployer(Deployer): |
| 7 | + """Expects TLS certificates to be managed on the server. |
| 8 | +
|
| 9 | + Validates that the configured certificate and key files |
| 10 | + exist on the remote host. Installs a systemd path unit |
| 11 | + that watches the certificate file and automatically |
| 12 | + restarts/reloads affected services when it changes. |
| 13 | + """ |
| 14 | + |
| 15 | + def __init__(self, cert_path, key_path): |
| 16 | + self.cert_path = cert_path |
| 17 | + self.key_path = key_path |
| 18 | + |
| 19 | + def configure(self): |
| 20 | + server.shell( |
| 21 | + name="Verify external TLS certificate and key exist", |
| 22 | + commands=[ |
| 23 | + f"test -f {self.cert_path} && test -f {self.key_path}", |
| 24 | + ], |
| 25 | + ) |
| 26 | + |
| 27 | + # Deploy the .path unit (templated with the cert path). |
| 28 | + source = get_resource("tls-cert-reload.path.f", pkg=__package__) |
| 29 | + content = source.read_text().format(cert_path=self.cert_path).encode() |
| 30 | + |
| 31 | + import io |
| 32 | + |
| 33 | + path_unit = files.put( |
| 34 | + name="Upload tls-cert-reload.path", |
| 35 | + src=io.BytesIO(content), |
| 36 | + dest="/etc/systemd/system/tls-cert-reload.path", |
| 37 | + user="root", |
| 38 | + group="root", |
| 39 | + mode="644", |
| 40 | + ) |
| 41 | + |
| 42 | + service_unit = files.put( |
| 43 | + name="Upload tls-cert-reload.service", |
| 44 | + src=get_resource("tls-cert-reload.service", pkg=__package__), |
| 45 | + dest="/etc/systemd/system/tls-cert-reload.service", |
| 46 | + user="root", |
| 47 | + group="root", |
| 48 | + mode="644", |
| 49 | + ) |
| 50 | + |
| 51 | + if path_unit.changed or service_unit.changed: |
| 52 | + self.need_restart = True |
| 53 | + |
| 54 | + def activate(self): |
| 55 | + systemd.service( |
| 56 | + name="Enable tls-cert-reload path watcher", |
| 57 | + service="tls-cert-reload.path", |
| 58 | + running=True, |
| 59 | + enabled=True, |
| 60 | + restarted=self.need_restart, |
| 61 | + daemon_reload=self.need_restart, |
| 62 | + ) |
| 63 | + # Always trigger a reload so services pick up the current cert. |
| 64 | + # The path unit handles future changes via inotify. |
| 65 | + server.shell( |
| 66 | + name="Reload TLS services for current certificate", |
| 67 | + commands=["systemctl start tls-cert-reload.service"], |
| 68 | + ) |
| 69 | + |
0 commit comments