pyinfra/tasks/ssh.py

45 lines
1 KiB
Python
Raw Normal View History

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
BASE_DIR = Path(__file__).parent.parent
def deploy_ssh_keys():
files.file(
name="Create authorized_keys file",
2024-06-08 00:53:33 +02:00
path="/root/.ssh/authorized_keys",
)
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,
)
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",
).changed
systemd.service(
name="Restart SSHD service",
service="ssh",
2024-06-08 00:53:33 +02:00
restarted=config_changed,
)
@deploy
def setup_ssh():
deploy_ssh_keys()
reconfigure_ssh()