Managing Systems and Applications with pyinfra
Getting Facts from Your Servers
You can also use the pyinfra CLI to determine the current state of your servers using facts. For instance, if you want to compare the installed version of the vim package on several Debian and Ubuntu systems, simply run
pyinfra nov.home,podpile.home fact deb.DebPackage package=vim
For each host in the inventory, this command returns the package version or null if the package isn't installed.
Server facts, in particular, are plentiful. For instance, you can query every system's kernel version with
pyinfra nov.home,podpile.home,microos.home,code.example.com fact server.KernelVersion
Or perhaps you need to identify which systems require a reboot:
pyinfra nov.home,podpile.home,microos.home fact server.RebootRequired
If you want to query multiple facts, just append them as additional arguments to the command line (without repeating fact). Explore the Facts Index [5] to discover all facts provided by pyinfra.
Creating an Inventory File
Up to this point, you haven't seen any Python code yet. The first thing you can do is specify your hosts in an inventory file. This file, typically named inventory.py, is a Python file where you can define host groups as a list, for example:
servers = ["podpile.home", "microos.home", "code.example.com"] workstations = ["nov.home", "tux.home"]
You can now use this inventory file instead of listing all hosts on the pyinfra CLI
pyinfra inventory.py fact server.RebootRequired
With host groups defined in the inventory file, you can also restrict pyinfra commands to a specific group. For example, install the vim package solely on your workstations:
pyinfra inventory.py --sudo server.packages vim --limit workstations
Creating a Deploy
In addition to specifying your hosts and groups in an inventory file, you can also define operations for these hosts in a deploy file, typically named deploy.py. For instance, the following deploy file ensures that a list of packages is installed on all hosts:
from pyinfra.operations import server server.packages( name="Install packages", packages=["tmux", "vim"], _sudo=True )
The _sudo argument specifies that the operation runs with sudo on the host, which is necessary to install packages.
You can now run this deploy on all hosts using
pyinfra inventory.py deploy.py
However, this prompts for a sudo password for each host. You can remedy this by adding the --same-sudo-password option:
pyinfra inventory.py deploy.py --same-sudo-password
After typing the sudo password once, pyinfra reuses the same password across all hosts. If succesful, all specified packages are now installed on your hosts.
Buy this article as PDF
(incl. VAT)