### Install packages using pacman.packages Source: https://docs.pyinfra.com/en/3.x/operations/pacman.html Demonstrates how to install specific packages using the pacman.packages operation. It includes an example of updating the package database before installation. ```python from pyinfra.operations import pacman pacman.packages( name="Install Vim and a plugin", packages=["vim-fugitive", "vim"], update=True, ) ``` -------------------------------- ### Setup Development Environment Source: https://docs.pyinfra.com/en/3.x/contributing.html Commands to clone the pyinfra repository and install dependencies in editable mode using uv. ```bash git clone git@github.com:pyinfra-dev/pyinfra.git cd pyinfra uv sync ``` -------------------------------- ### Install Nginx using @local Connector in pyinfra Source: https://docs.pyinfra.com/en/3.x/connectors/local.html This example demonstrates how to install the Nginx package on a local machine using the pyinfra CLI with the @local connector. It specifies the inventory file and the operation to perform, including updating packages and using sudo privileges. This connector is only compatible with MacOS & Linux hosts. ```bash pyinfra inventory.py apt.packages nginx update=true _sudo=true ``` -------------------------------- ### SSH Connector Examples Source: https://docs.pyinfra.com/en/3.x/connectors/ssh.html Examples demonstrating how to configure the SSH connector in an inventory file for various scenarios. ```APIDOC ## Examples An inventory file (`inventory.py`) containing a single SSH target with SSH forward agent enabled: ```python hosts = [ ("my-host.net", {"ssh_forward_agent": True}), ] ``` Multiple hosts sharing the same SSH username: ```python hosts = ( ["my-host-1.net", "my-host-2.net"], {"ssh_user": "ssh-user"}, ) ``` Multiple hosts with different SSH usernames: ```python hosts = [ ("my-host-1.net", {"ssh_user": "ssh-user"}), ("my-host-2.net", {"ssh_user": "other-user"}), ] ``` ``` -------------------------------- ### Retrieve Installable Architectures Source: https://docs.pyinfra.com/en/3.x/facts/opkg.html Returns a dictionary of architectures supported by the system and their associated installation priorities. ```python host.get_fact(OpkgInstallableArchitectures, ) ``` -------------------------------- ### Install .deb package with pyinfra Source: https://docs.pyinfra.com/en/3.x/operations/apt.html Demonstrates how to install a .deb package from a remote URL using the apt.deb operation. It assumes the target system has wget installed to fetch the package. ```python from pyinfra.operations import apt apt.deb( name="Install Chrome via deb", src="https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb", ) ``` -------------------------------- ### Get All Installed Debian Packages Fact with pyinfra Source: https://docs.pyinfra.com/en/3.x/facts/deb.html Returns a dictionary containing all installed dpkg packages on the system. The keys are package names and values are lists of their installed versions. ```python from pyinfra.facts.deb import DebPackages installed_packages = host.get_fact(DebPackages, ) # installed_packages will be in the format: {"package_name": ["version"]} ``` -------------------------------- ### pyinfra: Inventory File Examples for SSH Source: https://docs.pyinfra.com/en/3.x/connectors/ssh.html Provides examples of Python inventory files for pyinfra, showcasing different ways to define SSH targets. This includes setting SSH forward agent and specifying usernames for single or multiple hosts. ```python hosts = [ ("my-host.net", {"ssh_forward_agent": True}), ] ``` ```python hosts = ( ["my-host-1.net", "my-host-2.net"], {"ssh_user": "ssh-user"}, ) ``` ```python hosts = [ ("my-host-1.net", {"ssh_user": "ssh-user"}), ("my-host-2.net", {"ssh_user": "other-user"}), ] ``` -------------------------------- ### Install Packages with pyinfra CLI Source: https://docs.pyinfra.com/en/3.x/cli.html Demonstrates installing packages like 'nginx' on Ubuntu and Fedora systems using pyinfra's ad-hoc commands. It shows how to specify package managers and use sudo privileges. ```shell # Ubuntu example pyinfra inventory.py apt.packages nginx update=true _sudo=true # Fedora example pyinfra inventory2.py yum.packages nginx _sudo=true ``` -------------------------------- ### GET SnapPackages Source: https://docs.pyinfra.com/en/3.x/facts/snap.html Retrieves a list of all installed snap packages on the host. ```APIDOC ## GET snap.SnapPackages ### Description Returns a list of all installed snap packages on the target host. ### Method GET ### Endpoint host.get_fact(SnapPackages) ### Response #### Success Response (200) - **packages** (array) - A list of strings representing installed snap package names. #### Response Example [ "core", "core18", "core20", "lxd", "snapd" ] ``` -------------------------------- ### Define Inventory and Deploy Operations Source: https://docs.pyinfra.com/en/3.x/deploy-process.html Example of defining host groups and executing conditional package installations using pyinfra operations. This demonstrates how code is structured to run across multiple hosts. ```python web_servers = ["web-01", "web-02", "web-03"] db_server = ["db-01"] from pyinfra import host from pyinfra.operations import apt apt.packages( name="Install base debugging packages", packages=["htop", "iftop"], update=True, cache_time=3600, ) if "db_server" in host.groups: apt.packages( name="Install postgres server", packages=["postgresql-server"], ) if "web_servers" in host.groups: apt.packages( name="Install nginx", packages=["nginx"], ) ``` -------------------------------- ### Conditional Package Installation using Host Facts (pyinfra) Source: https://docs.pyinfra.com/en/3.x/using-operations.html Installs the 'nano' package using either 'yum' or 'apt' based on the detected Linux distribution (Fedora or Ubuntu) using host facts. Requires pyinfra to be installed. ```python from pyinfra import host from pyinfra.facts.server import LinuxName from pyinfra.operations import yum, apt if host.get_fact(LinuxName) == "Fedora": yum.packages( name="Install nano via yum", packages=["nano"], _sudo=True ) if host.get_fact(LinuxName) == "Ubuntu": apt.packages( name="Install nano via apt", packages=["nano"], update=True, _sudo=True ) ``` -------------------------------- ### GET apt.AptSources Source: https://docs.pyinfra.com/en/3.x/facts/apt.html Retrieves a list of all configured APT sources on the host. ```APIDOC ## GET apt.AptSources ### Description Returns a list of installed apt sources. ### Method GET ### Endpoint host.get_fact(AptSources) ### Response #### Success Response (200) - **sources** (array) - A list of objects representing each apt source. #### Response Example [ { "type": "deb", "url": "http://archive.ubuntu.org", "distribution": "trusty", "components": ["main", "multiverse"] } ] ``` -------------------------------- ### Install Chocolatey (choco.install) Source: https://docs.pyinfra.com/en/3.x/operations/choco.html Installs Chocolatey (choco) on the target system. This is a stateless operation, meaning it will always execute commands and is not idempotent. It inherits all global arguments. ```python choco.install(**kwargs) ``` -------------------------------- ### List All Installed Snap Packages with pyinfra Source: https://docs.pyinfra.com/en/3.x/facts/snap.html Retrieves a list of all snap packages currently installed on the host. This function returns a list of strings, where each string is the name of an installed snap package. ```python host.get_fact(SnapPackages, ) ``` -------------------------------- ### List All Installed Flatpak Packages with pyinfra Source: https://docs.pyinfra.com/en/3.x/facts/flatpak.html Retrieves a list of all installed Flatpak packages on the target system. This fact returns a list of strings, where each string is the name of an installed package. ```python host.get_fact(FlatpakPackages, ) ``` -------------------------------- ### Start OpenVZ Container with pyinfra Source: https://docs.pyinfra.com/en/3.x/operations/vzctl.html This operation starts an OpenVZ container. It is a stateless and non-idempotent operation. The container ID (ctid) is required, and an optional `force` argument can be provided. All global arguments are inherited. ```python vzctl.start(ctid: str, force=False, **kwargs) ``` -------------------------------- ### Install pyinfra Source: https://docs.pyinfra.com/en/3.x/getting-started.html The command to install the pyinfra tool using the uv package manager. ```bash uv tool install pyinfra ``` -------------------------------- ### pyinfra Inventory Connector Example Source: https://docs.pyinfra.com/en/3.x/api/connectors.html An example of an inventory-only connector for pyinfra. This class implements the `make_names_data` method to yield host information, including hostname, data, and groups. It's useful for integrating with external inventory sources. ```python from pyinfra.connectors.base import BaseConnector class InventoryConnector(BaseConnector): handles_execution = False @staticmethod def make_names_data(_=None): """ Generate inventory targets. Yields: tuple: (name, data, groups) """ # connect to api/parse files/process data here, resulting in a list of tuples; gathered_hosts = [ ('@local', {}, ['@local']), ('foundhost', {'ip': '198.51.100.4'}, ['remote', 'example']) ] for loop_host in gathered_hosts: yield loop_host[0], loop_host[1], loop_host[2] ``` -------------------------------- ### Retrieve Installed Pkg Packages Source: https://docs.pyinfra.com/en/3.x/facts/pkg.html This snippet demonstrates how to use the host.get_fact method to fetch a dictionary of installed packages. The output is structured as a mapping of package names to a list of their installed versions. ```python host.get_fact(PkgPackages) ``` ```json { "package_name": ["version"] } ``` -------------------------------- ### Retrieve Installed Packages Source: https://docs.pyinfra.com/en/3.x/facts/opkg.html Returns a dictionary mapping installed package names to their respective versions. ```python host.get_fact(OpkgPackages, ) ``` -------------------------------- ### Retrieve Installed Brew Packages Source: https://docs.pyinfra.com/en/3.x/facts/brew.html Fetches a dictionary of installed Homebrew packages from the host. The returned dictionary maps package names to a list containing their version. ```python host.get_fact(BrewPackages) ``` -------------------------------- ### Example usage of iptables rules Source: https://docs.pyinfra.com/en/3.x/operations/iptables.html Practical examples showing how to block SSH traffic and configure NAT routing using the iptables.rule operation. ```python from pyinfra.operations import iptables iptables.rule( name="Block SSH traffic", chain="INPUT", jump="DROP", destination_port=22, ) iptables.rule( name="NAT traffic on from 8.8.8.8:53 to 8.8.4.4:8080", chain="PREROUTING", jump="DNAT", table="nat", source="8.8.8.8", destination_port=53, to_destination="8.8.4.4:8080", ) ``` -------------------------------- ### List All Installed RPM Packages with pyinfra Source: https://docs.pyinfra.com/en/3.x/facts/rpm.html Fetches a dictionary of all installed RPM packages on a host using pyinfra's `host.get_fact` method with `RpmPackages`. The output maps package names to their versions. ```python host.get_fact(RpmPackages, ) ``` -------------------------------- ### Retrieve Installed Pkgin Packages Source: https://docs.pyinfra.com/en/3.x/facts/pkgin.html This snippet demonstrates how to use the host.get_fact method to fetch a dictionary of installed packages managed by pkgin. The returned data structure maps package names to their respective version strings. ```python host.get_fact(PkginPackages) ``` ```json { "package_name": ["version"] } ``` -------------------------------- ### snap.package Source: https://docs.pyinfra.com/en/3.x/operations/snap.html Manages the installation and removal of snap packages, supporting specific channels and confinement options. ```APIDOC ## snap.package ### Description Install or remove snap packages on the target system. This operation supports defining specific channels and enabling classic confinement. ### Method Python Operation ### Parameters #### Arguments - **packages** (str | list[str]) - Optional - The name or list of names of the snap packages to manage. - **channel** (str) - Optional - The tracking channel to use (default: "latest/stable"). - **classic** (bool) - Optional - Whether to use classic confinement (default: False). - **present** (bool) - Optional - Whether the package should be installed (default: True). ### Request Example ```python from pyinfra.operations import snap # Install vlc via snap snap.package( name="Install vlc", packages="vlc", ) # Install neovim with classic confinement snap.package( name="Install Neovim", packages="nvim", classic=True, ) ``` ### Response #### Success Response - **status** (bool) - Returns True if the operation resulted in a change or ensured the desired state. ``` -------------------------------- ### pyinfra CLI Usage Examples Source: https://docs.pyinfra.com/en/3.x/cli.html Demonstrates common pyinfra CLI commands for running deploys, single operations, executing arbitrary commands, and gathering facts. It shows how to specify inventory sources and operations. ```bash pyinfra INVENTORY deploy_web.py [deploy_db.py]... pyinfra INVENTORY server.user pyinfra home=/home/pyinfra pyinfra INVENTORY exec -- echo "hello world" pyinfra INVENTORY fact server.LinuxName [server.Users]... pyinfra INVENTORY fact files.File path=/path/to/file... pyinfra INVENTORY debug-inventory ``` -------------------------------- ### GET hardware.Memory Source: https://docs.pyinfra.com/en/3.x/facts/hardware.html Retrieves the total installed system memory in megabytes. ```APIDOC ## GET hardware.Memory ### Description Returns the total amount of memory installed in the server, expressed in MB. ### Method GET ### Endpoint host.get_fact(Memory) ### Response #### Success Response (200) - **memory** (integer) - Total memory in MB. ``` -------------------------------- ### apt.upgrade Source: https://docs.pyinfra.com/en/3.x/operations/apt.html Upgrades all installed apt packages on the system. ```APIDOC ## apt.upgrade ### Description Upgrades all apt packages. ### Method `apt.upgrade` ### Parameters #### Arguments - **auto_remove** (bool) - Optional - Removes transitive dependencies that are no longer needed. Defaults to False. ### Request Example ```python # Upgrade all packages apt.upgrade( name="Upgrade apt packages", ) # Upgrade all packages and remove unneeded transitive dependencies apt.upgrade( name="Upgrade apt packages and remove unneeded dependencies", auto_remove=True ) ``` ### Note This operation also inherits all global arguments. ``` -------------------------------- ### Install RPM Package from URL Source: https://docs.pyinfra.com/en/3.x/operations/dnf.html Installs an RPM package from a remote URL. It dynamically fetches the package source based on system facts like the CentOS version. ```python major_centos_version = host.get_fact(LinuxDistribution)["major"] dnf.rpm( name="Install EPEL rpm to enable EPEL repo", src=f"https://dl.fedoraproject.org/pub/epel/epel-release-latest-{major_centos_version}.noarch.rpm", ) ``` -------------------------------- ### GET FlatpakPackages Source: https://docs.pyinfra.com/en/3.x/facts/flatpak.html Retrieves a list of all installed Flatpak packages on the host. ```APIDOC ## GET flatpak.FlatpakPackages ### Description Returns a list of all Flatpak packages currently installed on the host. ### Method GET ### Endpoint host.get_fact(FlatpakPackages) ### Response #### Success Response (200) - **packages** (array) - A list of strings representing installed Flatpak package IDs. #### Response Example [ "org.gnome.Platform", "org.kde.Platform", "org.kde.Sdk", "org.libreoffice.LibreOffice", "org.videolan.VLC" ] ``` -------------------------------- ### GET SnapPackage Source: https://docs.pyinfra.com/en/3.x/facts/snap.html Retrieves detailed information for a specific installed snap package. ```APIDOC ## GET snap.SnapPackage ### Description Returns detailed information for a specific installed snap package. ### Method GET ### Endpoint host.get_fact(SnapPackage, package) ### Parameters #### Path Parameters - **package** (string) - Required - The name of the snap package to query. ### Response #### Success Response (200) - **name** (string) - The name of the package - **publisher** (string) - The publisher of the package - **snap-id** (string) - The unique snap identifier - **channel** (string) - The release channel - **version** (string) - The version of the package #### Response Example { "name": "lxd", "publisher": "Canonical✓", "snap-id": "J60k4JY0HppjwOjW8dZdYc8obXKxujRu", "channel": "4.0/stable", "version": "4.0.9" } ``` -------------------------------- ### Building and Viewing Documentation Source: https://docs.pyinfra.com/en/3.x/contributing.html Scripts to generate the public documentation and serve it locally for previewing. ```bash scripts/build-public-docs.sh uv run -m http.server -d docs/public/en/latest/ ``` -------------------------------- ### Get Choco Version Fact Source: https://docs.pyinfra.com/en/3.x/facts/choco.html Retrieves the installed version of Chocolatey (choco). ```APIDOC ## GET ChocoVersion Fact ### Description Retrieves the installed version of choco (Chocolatey). ### Method GET ### Endpoint `/facts/choco/version` (Conceptual - actual usage via `host.get_fact`) ### Parameters None ### Request Example ```python host.get_fact(ChocoVersion) ``` ### Response #### Success Response (200) - **version** (string) - The installed Chocolatey version string. #### Response Example ```json { "version": "1.3.0" } ``` ``` -------------------------------- ### GET FlatpakPackage Source: https://docs.pyinfra.com/en/3.x/facts/flatpak.html Retrieves detailed information for a specific installed Flatpak package. ```APIDOC ## GET flatpak.FlatpakPackage ### Description Returns metadata for a specific installed Flatpak package on the host. ### Method GET ### Endpoint host.get_fact(FlatpakPackage, package) ### Parameters #### Path Parameters - **package** (string) - Required - The ID of the Flatpak package to query. ### Response #### Success Response (200) - **id** (string) - The package ID. - **ref** (string) - The reference string for the package. - **version** (string) - The installed version of the package. #### Response Example { "id": "org.signal.Signal", "ref": "app/org.signal.Signal/x86_64/stable", "version": "7.12.0" } ``` -------------------------------- ### pacman.packages Source: https://docs.pyinfra.com/en/3.x/operations/pacman.html Manages the installation or removal of Arch Linux packages using pacman. ```APIDOC ## pacman.packages ### Description Add or remove pacman packages on the target system. ### Method Python Operation ### Parameters #### Request Body - **packages** (list[str]) - Optional - List of packages to ensure. - **present** (bool) - Optional - Whether the packages should be installed (default: True). - **update** (bool) - Optional - Run `pacman -Sy` before installing packages. - **upgrade** (bool) - Optional - Run `pacman -Su` before installing packages. ### Request Example from pyinfra.operations import pacman pacman.packages( name="Install Vim", packages=["vim"], update=True ) ``` -------------------------------- ### GET DnfRepositories Source: https://docs.pyinfra.com/en/3.x/facts/dnf.html Retrieves the list of installed DNF repositories from the target host. ```APIDOC ## GET dnf.DnfRepositories ### Description Retrieves a list of all configured DNF repositories on the target host, including their configuration details such as repoid, name, and enabled status. ### Method GET ### Endpoint host.get_fact(DnfRepositories) ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example ``` host.get_fact(DnfRepositories) ``` ### Response #### Success Response (200) - **repoid** (string) - The repository identifier. - **name** (string) - The human-readable name of the repository. - **enabled** (string) - Whether the repository is enabled (1 or 0). - **gpgcheck** (string) - Whether GPG check is enabled. #### Response Example [ { "repoid": "baseos", "name": "AlmaLinux $releasever - BaseOS", "mirrorlist": "https://mirrors.almalinux.org/mirrorlist/$releasever/baseos", "enabled": "1", "gpgcheck": "1", "countme": "1", "gpgkey": "file:///etc/pki/rpm-gpg/RPM-GPG-KEY-AlmaLinux-9", "metadata_expire": "86400", "enabled_metadata": "1" } ] ``` -------------------------------- ### Manage Docker Containers with pyinfra Source: https://docs.pyinfra.com/en/3.x/operations/docker.html Demonstrates how to create, start, stop, and configure Docker containers using the docker.container operation. It covers common parameters like image selection, port mapping, network attachment, and restart policies. ```python from pyinfra.operations import docker # Run a container docker.container( name="Deploy Nginx container", container="nginx", image="nginx:alpine", ports=["80:80"], present=True, force=True, networks=["proxy", "services"], volumes=["nginx_data:/usr/share/nginx/html"], pull_always=True, restart_policy="unless-stopped", auto_remove=True, ) # Stop a container docker.container( name="Stop Nginx container", container="nginx", start=False, ) # Start a container docker.container( name="Start Nginx container", container="nginx", start=True, ) ``` -------------------------------- ### Get Memory Information Source: https://docs.pyinfra.com/en/3.x/facts/hardware.html Retrieves the total installed memory of the server in megabytes (MB). This fact provides a simple way to get the system's RAM size. ```python host.get_fact(Memory, ) ``` -------------------------------- ### xbps.packages Source: https://docs.pyinfra.com/en/3.x/operations/xbps.html Manages the installation, removal, or update of XBPS packages. ```APIDOC ## xbps.packages ### Description Install, remove, or update XBPS packages on the target system. ### Method Operation (Python Function) ### Parameters #### Request Body - **packages** (list[str]) - Optional - List of package names to ensure. - **present** (bool) - Optional - Whether the packages should be installed (default: True). - **update** (bool) - Optional - Run `xbps-install -S` before installing packages. - **upgrade** (bool) - Optional - Run `xbps-install -y -u` before installing packages. ### Request Example ```python from pyinfra.operations import xbps xbps.packages( name="Install Vim and Vim Pager", packages=["vimpager", "vim"] ) ``` ``` -------------------------------- ### pyinfra Inventory Specification Examples Source: https://docs.pyinfra.com/en/3.x/cli.html Illustrates different methods for specifying inventory in pyinfra, including loading from a file, providing hostnames directly, using the local subprocess connector, and targeting Docker containers. ```bash # Load inventory hosts from a file pyinfra inventory.py ... # Execute via SSH against two servers pyinfra my-server.net,my-other-server.net ... # Execute on the local machine via subprocess pyinfra @local ... # Execute via local subprocess and a server over SSH pyinfra my-server.net,@local ... # Execute against a Docker container pyinfra @docker/fedora:43 ... ``` -------------------------------- ### Get Installed Gem Packages with pyinfra Source: https://docs.pyinfra.com/en/3.x/facts/gem.html Retrieves a dictionary of installed gem packages and their versions from a remote host using pyinfra's `GemPackages` fact. The output is a dictionary where keys are package names and values are lists of installed versions. ```python host.get_fact(GemPackages, ) ``` -------------------------------- ### Upload Files with Pyinfra Source: https://docs.pyinfra.com/en/3.x/operations/files.html Demonstrates how to upload a local file to a remote destination and how to upload dynamic content using a StringIO object. ```python files.put( name="Update the message of the day file", src="files/motd", dest="/etc/motd", mode="644", ) files.put( name="Upload a StringIO object", src=StringIO("file contents"), dest="/etc/motd", ) ``` -------------------------------- ### Get Choco Packages Fact Source: https://docs.pyinfra.com/en/3.x/facts/choco.html Retrieves a dictionary of installed Chocolatey packages and their versions. ```APIDOC ## GET ChocoPackages Fact ### Description Retrieves a dictionary of installed Chocolatey (choco) packages and their versions. ### Method GET ### Endpoint `/facts/choco/packages` (Conceptual - actual usage via `host.get_fact`) ### Parameters None ### Request Example ```python host.get_fact(ChocoPackages) ``` ### Response #### Success Response (200) - **packages** (dict) - A dictionary where keys are package names and values are lists of installed versions. #### Response Example ```json { "package_name": ["version"], "another_package": ["1.2.3", "1.2.4"] } ``` ``` -------------------------------- ### Get Choco Packages Fact in Python Source: https://docs.pyinfra.com/en/3.x/facts/choco.html Retrieves a dictionary of installed Chocolatey packages and their versions using pyinfra's host.get_fact function. This fact is useful for auditing installed software. ```python from pyinfra.facts.choco import ChocoPackages host.get_fact(ChocoPackages, ) ``` -------------------------------- ### Execute Localhost Operations via pyinfra API Source: https://docs.pyinfra.com/en/3.x/api/index.html Demonstrates how to initialize a pyinfra state, define an inventory, add operations like user creation and shell command execution, and run them against the localhost. It also shows how to retrieve operation results and system facts. ```python from pyinfra.api import Config, Inventory, State from pyinfra.api.connect import connect_all from pyinfra.api.operation import add_op from pyinfra.api.operations import run_ops from pyinfra.api.facts import get_facts from pyinfra.facts.server import Os from pyinfra.operations import server inventory = Inventory((["@local"], {})) config = Config(SUDO=True) state = State(inventory=inventory, config=config) connect_all(state) result1 = add_op( state, server.user, user="pyinfra", home="/home/pyinfra", shell="/bin/bash", ) result2 = add_op( state, server.shell, name="Run some shell commands", commands=["whoami", "echo $PATH", "bash --version"] ) run_ops(state) host = state.hosts.inventory['@local'] print(result1.changed, result1[host].stdout, result1[host].stderr) print(result2.changed, result2[host].stdout, result2[host].stderr) print(get_facts(state, Os)) ``` -------------------------------- ### GET Pip Facts Source: https://docs.pyinfra.com/en/3.x/facts/pip.html Retrieves information about installed pip or pip3 packages on a target host. ```APIDOC ## GET pip.PipPackages / pip.Pip3Packages ### Description Retrieves a dictionary of installed pip packages and their versions from the host. ### Method GET ### Endpoint host.get_fact(PipPackages, pip=None) or host.get_fact(Pip3Packages, pip=None) ### Parameters #### Query Parameters - **pip** (string) - Optional - The path to the specific pip executable if not in the system path. ### Request Example { "pip": "/usr/bin/pip3" } ### Response #### Success Response (200) - **dict** (object) - A dictionary where keys are package names and values are lists containing the installed version. #### Response Example { "requests": ["2.25.1"], "pyinfra": ["3.0.0"] } ``` -------------------------------- ### GET cargo.CargoPackages Source: https://docs.pyinfra.com/en/3.x/facts/cargo.html Retrieves a dictionary of all globally installed cargo packages and their versions from the target host. ```APIDOC ## GET cargo.CargoPackages ### Description Retrieves a dictionary of installed cargo packages globally on the target host. ### Method GET ### Endpoint cargo.CargoPackages ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example ```python host.get_fact(CargoPackages) ``` ### Response #### Success Response (200) - **packages** (dict) - A dictionary where keys are package names and values are lists of installed versions. #### Response Example { "package_name": ["version"] } ``` -------------------------------- ### Retrieve APT Sources Source: https://docs.pyinfra.com/en/3.x/facts/apt.html Lists all configured APT software sources on the host. Returns a list of dictionaries containing the source type, URL, distribution, and components. ```python host.get_fact(AptSources) ``` -------------------------------- ### GET apk.ApkPackages Source: https://docs.pyinfra.com/en/3.x/facts/apk.html Retrieves a dictionary of all installed APK packages and their corresponding versions from the target host. ```APIDOC ## GET apk.ApkPackages ### Description Retrieves a dictionary of installed APK packages on the target host. The keys are package names and the values are lists containing the version strings. ### Method GET ### Endpoint host.get_fact(ApkPackages) ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example ```python host.get_fact(ApkPackages) ``` ### Response #### Success Response (200) - **dict** (object) - A dictionary where keys are package names and values are lists of version strings. #### Response Example { "package_name": ["version"] } ``` -------------------------------- ### Manage Zypper Repositories Source: https://docs.pyinfra.com/en/3.x/operations/zypper.html Shows how to add repositories either by downloading a remote .repo file via URL or by manually constructing the repository configuration using a base URL. ```python from pyinfra.operations import zypper # Download a repository file zypper.repo( name="Install container virtualization repo via URL", src="https://download.opensuse.org/repositories/Virtualization:containers/openSUSE_Tumbleweed/Virtualization:containers.repo", ) # Create the repository file from baseurl/etc zypper.repo( name="Install container virtualization repo", src="Virtualization:containers (openSUSE_Tumbleweed)", baseurl="https://download.opensuse.org/repositories/Virtualization:/containers/openSUSE_Tumbleweed/", ) ``` -------------------------------- ### Get Npm Packages Fact with pyinfra Source: https://docs.pyinfra.com/en/3.x/facts/npm.html Retrieves a dictionary of installed npm packages using pyinfra's `get_fact` method. This fact can be used to query globally installed packages or those within a specific directory. The output is a dictionary where keys are package names and values are lists of their installed versions. ```python host.get_fact(NpmPackages, directory=None) ``` -------------------------------- ### Implementing run_shell_command with Command Wrapping Source: https://docs.pyinfra.com/en/3.x/api/connectors.html Shows the recommended pattern for implementing run_shell_command using pyinfra's utility functions. It demonstrates extracting control arguments and using make_unix_command_for_host to ensure shell operators and sudo are handled correctly. ```python from pyinfra.connectors.util import extract_control_arguments, make_unix_command_for_host class MyConnector(BaseConnector): handles_execution = True def run_shell_command( self, command: StringCommand, print_output: bool = False, print_input: bool = False, **arguments: Unpack["ConnectorArguments"], ) -> Tuple[bool, CommandOutput]: control_args = extract_control_arguments(arguments) wrapped_command = make_unix_command_for_host( self.state, self.host, command, **arguments, ) timeout = control_args.get("_timeout") success_exit_codes = control_args.get("_success_exit_codes", [0]) exit_code, output = self._execute(wrapped_command, timeout=timeout) success = exit_code in success_exit_codes return success, output ``` -------------------------------- ### Include Files in pyinfra Deployments Source: https://docs.pyinfra.com/en/3.x/using-operations.html Shows how to use `local.include` to break down pyinfra deployment logic into multiple files, promoting modularity and organization. ```python from pyinfra import local ``` -------------------------------- ### Retrieve SELinux Port Type Source: https://docs.pyinfra.com/en/3.x/facts/selinux.html Gets the SELinux type associated with a specific protocol and port number. Requires the policycoreutils-dev package to be installed. ```python host.get_fact(SEPort, protocol, port) ``` -------------------------------- ### Manage Flatpak packages with pyinfra Source: https://docs.pyinfra.com/en/3.x/operations/flatpak.html Demonstrates how to install single or multiple Flatpak packages, specify a remote source, and remove existing packages using the pyinfra flatpak module. ```python from pyinfra.operations import flatpak # Install vlc flatpak flatpak.package( name="Install vlc", packages="org.videolan.VLC", ) # Install vlc flatpak from flathub flatpak.package( name="Install vlc", packages="org.videolan.VLC", remote="flathub", ) # Install multiple flatpaks flatpak.package( name="Install vlc and kodi", packages=["org.videolan.VLC", "tv.kodi.Kodi"], ) # Remove vlc flatpak.package( name="Remove vlc", packages="org.videolan.VLC", present=False, ) ``` -------------------------------- ### Define System State Source: https://docs.pyinfra.com/en/3.x/getting-started.html Examples of using pyinfra operations to enforce a desired state on remote hosts, such as installing packages or managing service status. ```bash pyinfra my-server.net dnf.packages vim pyinfra my-server.net init.systemd httpd running=False _sudo=True ``` -------------------------------- ### Manage Upstart Service State with pyinfra Source: https://docs.pyinfra.com/en/3.x/operations/upstart.html This Python code snippet demonstrates how to manage the state of an upstart service using pyinfra. It allows you to ensure a service is running, stopped, restarted, or reloaded, and can also manage whether the service is enabled to start on boot. Dependencies include the pyinfra library. Inputs are service name and desired state parameters. Limitations may exist depending on the specific upstart configuration. ```python from pyinfra.operations import upstart # Ensure a service is running and enabled on boot upstart.service(name='my-service', running=True, enabled=True) # Ensure a service is stopped and disabled on boot upstart.service(name='another-service', running=False, enabled=False) # Reload a running service upstart.service(name='my-service', running=True, reloaded=True) # Restart a running service upstart.service(name='my-service', running=True, restarted=True) # Execute a custom command for a service upstart.service(name='my-service', command='restart') ``` -------------------------------- ### Get All Docker Plugins Facts - pyinfra Source: https://docs.pyinfra.com/en/3.x/facts/docker.html Retrieves `docker plugin inspect` output for all Docker plugins on the host. This provides a list of all installed plugins and their details. ```python host.get_fact(DockerPlugins, ) ``` -------------------------------- ### Import and Execute a Packaged Deploy Source: https://docs.pyinfra.com/en/3.x/api/deploys.html Shows how to import a custom deploy function from a module and execute it, including passing global arguments like sudo. ```python from packaged_deploy import install_mariadb # Execute with default settings install_mariadb() # Execute with global arguments install_mariadb(sudo=True) ``` -------------------------------- ### Get Base Flatpak Fact with pyinfra Source: https://docs.pyinfra.com/en/3.x/facts/flatpak.html Retrieves the base Flatpak fact from a host using pyinfra. This fact provides general information about the Flatpak installation on the target system. ```python host.get_fact(FlatpakBaseFact) ``` -------------------------------- ### Configure Privilege Escalation with Sudo Source: https://docs.pyinfra.com/en/3.x/arguments.html Demonstrates how to use global arguments to execute operations with sudo privileges, including optional password specification. ```python # Execute a command with sudo server.user( name="Create pyinfra user using sudo", user="pyinfra", _sudo=True, ) # Execute a command with a specific sudo password server.user( name="Create pyinfra user using sudo", user="pyinfra", _sudo=True, _sudo_password="my-secret-password", ) ``` -------------------------------- ### Execute Puppet Agent with pyinfra Source: https://docs.pyinfra.com/en/3.x/operations/puppet.html Demonstrates how to invoke the puppet.agent operation. Includes a basic execution example and a more advanced configuration specifying a custom name and expected success exit codes. ```python from pyinfra.operations import puppet # Basic execution puppet.agent() # Execution with custom name and success exit codes # 0=no changes or 2=changes applied puppet.agent( name="Run the puppet agent", success_exit_codes=[0, 2], ) ``` -------------------------------- ### Get Docker System Info Fact - pyinfra Source: https://docs.pyinfra.com/en/3.x/facts/docker.html Retrieves `docker system info` output in JSON format. This fact provides comprehensive information about the Docker installation and its environment. ```python host.get_fact(DockerSystemInfo, ) ``` -------------------------------- ### Get Debian Package Information Fact with pyinfra Source: https://docs.pyinfra.com/en/3.x/facts/deb.html Fetches information about a specific .deb archive or an installed Debian package. This allows for detailed inspection of package status and details. ```python from pyinfra.facts.deb import DebPackage host.get_fact(DebPackage, package) ``` -------------------------------- ### Manage Zypper Packages Source: https://docs.pyinfra.com/en/3.x/operations/zypper.html Demonstrates how to update the package list and install specific packages, as well as how to ensure packages are at their latest version. ```python zypper.packages( name="Install Vim and Vim enhanced", packages=["vim-enhanced", "vim"], update=True, ) zypper.packages( name="Install latest Vim", packages=["vim"], latest=True, ) ``` -------------------------------- ### Get Choco Version Fact in Python Source: https://docs.pyinfra.com/en/3.x/facts/choco.html Retrieves the installed Chocolatey (choco) version using pyinfra's host.get_fact function. This fact is useful for checking compatibility or version requirements. ```python from pyinfra.facts.choco import ChocoVersion host.get_fact(ChocoVersion, ) ``` -------------------------------- ### Using the @podman Connector Source: https://docs.pyinfra.com/en/3.x/connectors/podman.html Examples of how to invoke pyinfra with the @podman connector to target Podman images or containers. ```APIDOC ## Using the @podman Connector ### Description This section demonstrates how to use the `@podman` connector with pyinfra to manage Podman resources. You can target specific images or running container IDs. ### Method Command Line Interface (CLI) ### Endpoint N/A (CLI command) ### Parameters #### CLI Arguments - **`@podman/:`** (string) - Required - The name and tag of the Podman image to use as a base. - **`@podman/`** (string) - Required - The ID of an existing running Podman container to target. ### Request Example ```bash # A Podman base image must be provided pyinfra @podman/alpine:3.8 # pyinfra can run on multiple Docker images in parallel pyinfra @podman/alpine:3.8,@podman/ubuntu:bionic # Execute against a running container pyinfra @podman/2beb8c15a1b1 ``` ### Response N/A (CLI execution) #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Get FreeBSD PkgPackage Fact with pyinfra Source: https://docs.pyinfra.com/en/3.x/facts/freebsd.html Retrieves information about a specific package installed on a FreeBSD host using pyinfra. It takes the package name as an argument and optionally a jail name. ```python host.get_fact(PkgPackage, package, jail=None) ``` -------------------------------- ### pyinfra Real-time Log Debugging Example Source: https://docs.pyinfra.com/en/3.x/cli.html Shows how to use `pyinfra exec` with the `--sudo` option and `tail -f` to stream logs from multiple remote servers in real-time, useful for debugging distributed systems. ```bash pyinfra inventory.py exec --sudo -- tail -f /var/log/elasticsearch/elasticsearch.log ``` -------------------------------- ### Get Specific Flatpak Package Info with pyinfra Source: https://docs.pyinfra.com/en/3.x/facts/flatpak.html Retrieves information for a specific installed Flatpak package. This function takes the package name as an argument and returns a dictionary containing the package's ID, reference, and version. ```python host.get_fact(FlatpakPackage, package) ``` -------------------------------- ### pyinfra CLI Limit Inventory Examples Source: https://docs.pyinfra.com/en/3.x/cli.html Demonstrates how to use the --limit argument to restrict pyinfra execution to specific hosts or groups within the inventory. Supports exact hostnames, glob patterns, and group names. ```bash # Only execute against @local pyinfra inventory.py deploy.py --limit @local # Only execute against hosts in the `app_servers` group pyinfra inventory.py deploy.py --limit app_servers # Only execute against hosts with names matching db* pyinfra inventory.py deploy.py --limit "db*" # Combine multiple limits pyinfra inventory.py deploy.py --limit app_servers --limit db-1.net ``` -------------------------------- ### Get Specific Snap Package Info with pyinfra Source: https://docs.pyinfra.com/en/3.x/facts/snap.html Retrieves detailed information for a specific installed snap package. It takes the package name as an argument and returns a JSON object with details like name, publisher, version, and channel. ```python host.get_fact(SnapPackage, package) ``` -------------------------------- ### Enable SysV Init Service Source: https://docs.pyinfra.com/en/3.x/operations/sysvinit.html Configures a service to start or stop at specific runlevels by creating the appropriate links in /etc/rcX.d/ directories. ```python sysvinit.enable( service="rsyslog", start_priority=20, stop_priority=80, start_levels=(2, 3, 4, 5), stop_levels=(0, 1, 6) ) # Example usage: init.d_enable( name="Finer control on which runlevels rsyslog should run", service="rsyslog", start_levels=(3, 4, 5), stop_levels=(0, 1, 2, 6) ) ``` -------------------------------- ### Get Zypper Repositories Fact - Python Source: https://docs.pyinfra.com/en/3.x/facts/zypper.html Retrieves a list of installed zypper repositories using pyinfra's `host.get_fact` method. This fact returns details such as repository ID, name, enabled status, autorefresh status, and base URL for each repository. It requires the `ZypperRepositories` fact to be available on the target system. ```python from pyinfra.facts.zypper import ZypperRepositories # Assuming 'host' is an initialized pyinfra host object repositories = host.get_fact(ZypperRepositories) # 'repositories' will be a list of dictionaries, e.g.: # [ # { # "repoid": "repo-oss", # "name": "Main Repository", # "enabled": "1", # "autorefresh": "1", # "baseurl": "http://download.opensuse.org/distribution/leap/$releasever/repo/oss/" # }, # ] ``` -------------------------------- ### Modularizing Deploys with local.include Source: https://docs.pyinfra.com/en/3.x/examples/groups_roles.html Learn how to conditionally include task files based on host group membership to organize complex infrastructure deployments. ```APIDOC ## pyinfra.local.include ### Description Allows the inclusion of external task files into the main deployment script. This is useful for separating roles (e.g., web vs database) and keeping the codebase clean. ### Method Python Module Call ### Parameters #### Arguments - **filename** (string) - Required - The path to the python file containing pyinfra operations to execute. ### Request Example ```python from pyinfra import host, local # Include tasks only for specific groups if 'web_servers' in host.groups: local.include('tasks/web.py') ``` ### Response #### Success Response - **Execution** (void) - The operations defined in the included file are added to the current operation batch for the target hosts. ``` -------------------------------- ### apt.ppa Source: https://docs.pyinfra.com/en/3.x/operations/apt.html Adds or removes Ubuntu PPA repositories. This operation is stateless and will always execute commands. ```APIDOC ## apt.ppa ### Description Add/remove Ubuntu ppa repositories. ### Method `apt.ppa` ### Parameters #### Arguments - **src** (str) - Required - The PPA name (full ppa:user/repo format). - **present** (bool) - Optional - Whether it should exist. Defaults to True. ### Request Example ```python # Note: Assumes software-properties-common is installed. apt.ppa( name="Add the Bitcoin ppa", src="ppa:bitcoin/bitcoin", ) ``` ### Note Requires `apt-add-repository` on the remote host. This operation also inherits all global arguments. ``` -------------------------------- ### Execute Deploy via CLI Source: https://docs.pyinfra.com/en/3.x/using-operations.html Example command to execute a pyinfra deploy script against a Docker container target. ```bash pyinfra @docker/ubuntu:20.04 deploy.py ``` -------------------------------- ### Retrieve Installed Pipx Packages Source: https://docs.pyinfra.com/en/3.x/facts/pipx.html Uses the PipxPackages fact to return a dictionary of installed pipx packages and their versions. The output maps package names to a list containing the installed version. ```python host.get_fact(PipxPackages, ) ``` -------------------------------- ### apt.repo Source: https://docs.pyinfra.com/en/3.x/operations/apt.html Adds or removes apt repositories from the system's sources list. ```APIDOC ## apt.repo ### Description Add/remove apt repositories. ### Method `apt.repo` ### Parameters #### Arguments - **src** (str) - Required - Apt source string eg `deb http://X hardy main`. - **present** (bool) - Optional - Whether the repo should exist on the system. Defaults to True. - **filename** (str | None) - Optional - Filename to use for the sources list entry. Defaults to `/etc/apt/sources.list`. ### Request Example ```python apt.repo( name="Install VirtualBox repo", src="deb https://download.virtualbox.org/virtualbox/debian bionic contrib", ) ``` ### Note This operation also inherits all global arguments. ``` -------------------------------- ### pyinfra.api.host Methods Source: https://docs.pyinfra.com/en/3.x/genindex.html Documentation for methods available on the pyinfra.api.host.Host object. ```APIDOC ## pyinfra.api.host Methods ### Description Methods for interacting with hosts via the pyinfra.api.host.Host object. ### Methods - **put_file()** (method) - Uploads a file to the host. - **run_shell_command()** (method) - Executes a shell command on the host. ### Properties - **print_prefix** (property) - Gets or sets the print prefix for host output. ``` -------------------------------- ### Retrieve Installed Locales Source: https://docs.pyinfra.com/en/3.x/facts/server.html Returns a list of all locales currently installed on the target host. ```python host.get_fact(Locales, ) ``` -------------------------------- ### Create a Python Deploy Source: https://docs.pyinfra.com/en/3.x/getting-started.html Defining inventory and operations in Python files to create reusable deployment configurations. ```python # inventory.py my_hosts = [ ("ubuntu2204", { "ssh_port": 2222, "ssh_hostname": "localhost", "ssh_user": "vagrant", "_sudo": True }), "my-server.net", "@docker/ubuntu:22.04" ] # deploy.py from pyinfra.operations import apt, server apt.packages( name="Ensure the vim apt package is installed", packages=["vim"], update=True, ) ``` ```bash pyinfra inventory.py deploy.py ``` -------------------------------- ### Executing pyinfra against Podman containers Source: https://docs.pyinfra.com/en/3.x/connectors/podman.html Examples of using the @podman connector via the CLI to target images or existing container IDs. This allows for rapid local iteration and testing of deployment operations. ```bash # A Podman base image must be provided pyinfra @podman/alpine:3.8 ... # pyinfra can run on multiple Docker images in parallel pyinfra @podman/alpine:3.8,@podman/ubuntu:bionic ... # Execute against a running container pyinfra @podman/2beb8c15a1b1 ... ``` -------------------------------- ### Manage Runit Service Auto Start Source: https://docs.pyinfra.com/en/3.x/operations/runit.html Controls whether a runit service starts automatically on boot by managing the 'service/down' file. It takes the service name and a boolean to indicate auto-start status. Defaults to starting automatically. ```python runit.auto(service: str, auto: bool=True, sourcedir: str="/etc/sv", **kwargs) ``` -------------------------------- ### Implementing Inventory Data Loading with make_names_data Source: https://docs.pyinfra.com/en/3.x/api/connectors.html Demonstrates how to implement the staticmethod make_names_data to supply inventory data. It highlights the need to handle external configuration access outside the static method scope. ```python def load_settings(): settings = {} # logic here return settings class InventoryConnector(BaseConnector): api_instance = external.ApiClient() @staticmethod def make_names_data(_=None): api_client = getattr(InventoryConnector, 'api_instance') api_settings = load_settings() # implementation logic ```