Skip to main content
Operations are the core building blocks of pyinfra. They define the desired state of your infrastructure and pyinfra ensures that state is achieved. This guide covers everything you need to know about using operations effectively.

What Are Operations?

Operations are Python functions that:
  • Define the desired state of a system (e.g., “package X should be installed”)
  • Generate shell commands to achieve that state
  • Are idempotent - running them multiple times produces the same result
  • Can detect changes before applying them (dry-run mode)

Basic Operation Usage

Importing Operations

Operations are organized by category in the pyinfra.operations module:

Calling Operations

Every operation call should include a descriptive name parameter:
The name parameter is required and helps you identify operations in pyinfra’s output.

Common Operations

Package Management

File Operations

System Operations

Git Operations

Global Arguments

Global arguments (prefixed with _) control how operations are executed:

Common Global Arguments

Global arguments are prefixed with underscore (_) to distinguish them from operation-specific parameters.

Operation Return Values

Operations return metadata that you can use for conditional execution:
Use did_change() to check if an operation made changes, enabling smart service restarts and conditional operations.

Working with Templates

pyinfra uses Jinja2 for templating:
1

Create a template file

Create templates/nginx.conf.j2:
templates/nginx.conf.j2
2

Use template in deploy

deploy.py

Combining Operations

Build complex deployments by combining multiple operations:
deploy.py

Operation Categories

pyinfra includes operations for many common tasks:

Best Practices

Always name your operations - Use descriptive names that explain what the operation does:
Use idempotent operations - Prefer state-defining operations over raw shell commands:
Check return values for conditional execution - Use operation return values to create smart workflows:

Next Steps