from typing import Optional from pyinfra import host from pyinfra.api import deploy from pyinfra.operations import dnf, systemd, server from pyinfra.facts.server import LinuxName, LinuxDistribution @deploy("Install PostgreSQL", data_defaults={"postgresql_version": 15}) def install(): linux_name = host.get_fact(LinuxName) version = host.data.postgresql_version if linux_name == "Fedora": fedora_release = host.get_fact(LinuxDistribution)["major"] dnf.rpm( f"https://download.postgresql.org/pub/repos/yum/reporpms/F-{fedora_release}-x86_64/pgdg-fedora-repo-latest.noarch.rpm" ) result = dnf.packages( name=f"Install psql {version} packages", packages=[ f"postgresql{version}", f"postgresql{version}-server", f"postgresql{version}-contrib", ], ) if result.changed: server.shell( name="initialize pgsql db", commands=[ f"/usr/pgsql-{version}/bin/postgresql-{version}-setup initdb" ], ) systemd.service( name="install psql {version} unit", service=f"postgresql-{version}", running=True, enabled=True, daemon_reload=True, ) else: raise AssertionError(f"Unsupported linux_name{linux_name}")