Skip to main content

Overview

The State class is the central coordinator for pyinfra deployments. It manages the entire deployment lifecycle, tracks operations across all hosts, coordinates parallel execution, and maintains the current execution stage.
Every pyinfra deployment has exactly one State instance that orchestrates all operations, hosts, and connectors.

State Class Definition

From src/pyinfra/api/state.py:145-283:

State Initialization

Creating and initializing a State:

Initialization Process

From src/pyinfra/api/state.py:206-283:

State Stages

State progresses through five distinct stages:

Stage Transitions

Stages can only move forward:

Operation Tracking

State maintains three levels of operation data:

StateOperationMeta

Shared metadata about an operation across all hosts:
Accessing operation metadata:

StateOperationHostData

Host-specific operation data:
Accessing host operation data:

StateHostMeta

Statistics about operations on a host:
Accessing host metadata:

StateHostResults

Execution results for a host:
Accessing results:

Host Management

Activating Hosts

Failing Hosts

Limiting Hosts

Usage:

Operation Ordering (DAG)

State builds a Directed Acyclic Graph (DAG) of operations to determine execution order:

DAG Example

Parallel Execution

State uses gevent for concurrent execution:

Parallel Pools

Example parallel execution:

Callback System

State supports callbacks for monitoring execution:

Registering Callbacks

Triggering Callbacks

Warning Tracking

State tracks warnings per stage:
Usage:

State Accessors

Operation Methods

Host Methods

Configuration

State holds a reference to the Config object:
Control output verbosity:
Usage:

State in API Mode

Using State programmatically:

State Lifecycle

Complete lifecycle:

Best Practices

One State Per Deploy

Create a single State instance for each deployment. Don’t reuse State objects.

Initialize Early

Initialize State with inventory and config before any operations.

Monitor Callbacks

Use callbacks for logging, metrics, and monitoring deployment progress.

Check Results

Always check execution results after deployment to verify success.

Handle Failures

Set FAIL_PERCENT to control how many host failures are acceptable.

Limit When Needed

Use limit_hosts to restrict operations to specific hosts during debugging.

Common Patterns

Progress Tracking

Error Collection

Dry Run

Architecture

Understand how State coordinates the two-phase execution model

Operations

Learn how operations are tracked in State

Inventory

See how State manages hosts and groups

Connectors

Understand how State coordinates connector execution