Esempi Pyinfra
Esempi Pyinfra
Pagina operativa con esempi minimi e riusabili per iniziare a usare pyinfra.
Struttura minima
Esempio di file:
inventory.py deploy.py
Inventory semplice
web_servers = [
"web-01.example.net",
"web-02.example.net",
]
db_servers = [
("db-01.example.net", {"install_postgres": True}),
]
Deploy semplice
from pyinfra.operations import apt, server
apt.packages(
name="Install packages",
packages=["vim", "curl"],
update=True,
)
server.shell(
name="Show uptime",
commands=["uptime"],
)
Esecuzione:
pyinfra inventory.py deploy.py
Esempio con gruppi
from pyinfra import host, local
from pyinfra.operations import server
if 'web_servers' in host.groups:
local.include('tasks/web.py')
if 'db_servers' in host.groups:
local.include('tasks/database.py')
server.shell(
name="Run everywhere",
commands=["hostname"],
)
Esempio con dati host
Inventory:
app_servers = [
("app-01.example.net", {"install_nginx": True}),
("app-02.example.net", {"install_nginx": False}),
]
Deploy:
from pyinfra import host
from pyinfra.operations import apt
if host.data.get("install_nginx"):
apt.packages(
name="Install nginx",
packages=["nginx"],
update=True,
)
Esempio local machine
pyinfra @local exec -- echo "hello world"
Esempio su container Docker
pyinfra @docker/ubuntu:22.04 exec -- uname -a
Esempio installazione file
from pyinfra.operations import files
files.file(
name="Ensure app log exists",
path="/var/log/app.log",
user="app",
group="app",
mode="644",
)
Esempio service management
from pyinfra.operations import systemd
systemd.service(
name="Ensure nginx is running",
service="nginx",
running=True,
enabled=True,
)
Esempio dry-run
pyinfra inventory.py deploy.py --dry
Note pratiche
- tenere `inventory.py` e `deploy.py` in Git
- usare `host.data` per differenziare host simili
- separare task complessi in file inclusi
- usare `--dry` prima dei deploy reali