2023-10-04 21:42:20 +02:00
|
|
|
from pathlib import Path
|
|
|
|
|
|
|
|
from pyinfra.api import deploy
|
2024-06-08 00:53:33 +02:00
|
|
|
from pyinfra.operations import files
|
|
|
|
from pyinfra.operations import systemd
|
2023-10-04 21:42:20 +02:00
|
|
|
|
|
|
|
BASE_DIR = Path(__file__).parent.parent
|
|
|
|
|
2024-01-13 14:36:17 +01:00
|
|
|
|
2023-10-04 21:42:20 +02:00
|
|
|
def deploy_ssh_keys():
|
|
|
|
files.file(
|
|
|
|
name="Create authorized_keys file",
|
2024-06-08 00:53:33 +02:00
|
|
|
path="/root/.ssh/authorized_keys",
|
2023-10-04 21:42:20 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
for key_path in BASE_DIR.glob("pubkeys/*.pub"):
|
|
|
|
with open(key_path, "r") as f:
|
|
|
|
key = f.read().strip()
|
|
|
|
files.line(
|
|
|
|
name=f"Adding key {key_path.name} to /root/.ssh/authorized_keys",
|
|
|
|
path="/root/.ssh/authorized_keys",
|
2024-06-08 00:53:33 +02:00
|
|
|
line=key,
|
2023-10-04 21:42:20 +02:00
|
|
|
)
|
|
|
|
|
2024-01-13 14:36:17 +01:00
|
|
|
|
2023-10-04 21:42:20 +02:00
|
|
|
def reconfigure_ssh():
|
|
|
|
config_changed = files.line(
|
|
|
|
name="Disable password login",
|
|
|
|
path="/etc/ssh/sshd_config",
|
|
|
|
line="PasswordAuthentication .+",
|
2024-06-08 00:53:33 +02:00
|
|
|
replace="PasswordAuthentication no",
|
2023-10-04 21:42:20 +02:00
|
|
|
).changed
|
|
|
|
|
|
|
|
systemd.service(
|
|
|
|
name="Restart SSHD service",
|
|
|
|
service="ssh",
|
2024-06-08 00:53:33 +02:00
|
|
|
restarted=config_changed,
|
2023-10-04 21:42:20 +02:00
|
|
|
)
|
|
|
|
|
2024-01-13 14:36:17 +01:00
|
|
|
|
2023-10-04 21:42:20 +02:00
|
|
|
@deploy
|
|
|
|
def setup_ssh():
|
|
|
|
deploy_ssh_keys()
|
|
|
|
reconfigure_ssh()
|