Skip to main content
pyinfra is a powerful infrastructure automation tool that turns Python code into shell commands and runs them on your servers. This tutorial will guide you through installing pyinfra and creating your first deploy.

What You’ll Learn

By the end of this tutorial, you’ll be able to:
  • Install and configure pyinfra
  • Execute ad-hoc commands on remote hosts
  • Create inventory files to manage hosts
  • Write deploy files with operations
  • Understand pyinfra’s idempotent state management

Installation

1

Install pyinfra with uv

The recommended way to install pyinfra is using uv:
You can also install pyinfra with pip: pip install pyinfra
2

Verify installation

Verify that pyinfra is installed correctly:

Your First pyinfra Command

Let’s start with some simple ad-hoc commands. The CLI always takes arguments in order: INVENTORY then OPERATIONS.

Execute Commands Locally

Test pyinfra on your local machine:
The @local connector executes commands on your local machine. This is perfect for testing!

Execute Commands via SSH

Connect to a remote server via SSH:
With SSH options:

Execute Commands in Docker

Run commands in a new Docker container:

Using Operations

Operations are pyinfra’s way of defining desired state. Unlike raw commands, operations are idempotent - they only make changes when necessary.

Install a Package

Run this command twice - the second time, pyinfra will detect that iftop is already installed and report no changes needed.

Creating Your First Deploy

Now let’s create a reusable deploy that you can save and version control.
1

Create an inventory file

Create a file named inventory.py to define your target hosts:
inventory.py
You can also define hosts with custom connection parameters:
2

Create a deploy file

Create a file named deploy.py with your operations:
deploy.py
3

Run your deploy

Execute your deploy file against your inventory:
pyinfra will connect to each host, detect what changes need to be made, and apply them in parallel across all hosts.
4

Run in dry-run mode

Before making actual changes, you can preview what pyinfra will do:
This shows you exactly what commands will be executed without actually running them.

Understanding the Output

When you run a deploy, pyinfra provides detailed output:

Advanced Inventory with Groups

As your infrastructure grows, you can organize hosts into groups:
inventory.py
Then target specific groups in your deploy:
deploy.py

Next Steps

Now that you understand the basics, explore more advanced topics:

Common Patterns

Keep your deploy files in version control (git) so you can track changes to your infrastructure over time!