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:
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: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
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
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
deploy.py
Next Steps
Now that you understand the basics, explore more advanced topics:- Using Operations - Learn about all available operations
- Inventory and Data - Master inventory management and data injection
- Deploying Applications - Build complete application deployments
- Idempotent Operations - Understand state management
- Parallel Execution - Optimize performance for large infrastructures
