Skip to main content
pyinfra’s API enables you to use pyinfra programmatically in Python scripts and applications. This allows you to build custom deployment tools, integrate with other systems, and create reusable infrastructure components.

Core Components

The pyinfra API is organized into several key modules:

Operations & Deploys

  • @operation - Decorator for creating custom operations
  • @deploy - Decorator for creating reusable deploy functions
  • add_op - Programmatically add operations to state
  • add_deploy - Programmatically add deploys to state

State Management

  • State - Manages the state of a pyinfra deployment
  • Inventory - Represents a collection of target hosts
  • Host - Represents a single target host
  • Config - Configuration options for deployments

Commands

Connectors

Connectors handle communication with target hosts:
  • SSH - Connect via SSH (default)
  • Local - Execute on local machine
  • Docker - Execute in Docker containers
  • Terraform - Generate inventory from Terraform
  • Vagrant - Generate inventory from Vagrant

Facts

Facts gather information about target hosts:

Quick Start

Here’s a simple example using the pyinfra API:

CLI vs API Mode

pyinfra operates in two modes:
  • CLI Mode - When running pyinfra command-line tool
  • API Mode - When using pyinfra as a Python library
Some functions behave differently depending on the mode:
  • add_op() and add_deploy() should only be called in API mode
  • Operations automatically execute immediately in API mode when called during the execute phase

Context Management

pyinfra uses context variables to track the current state, host, and config:

Type Safety

pyinfra includes type hints for better IDE support and type checking:

Next Steps

Explore the detailed API reference:
  • Operations - Create custom operations
  • Deploy - Create reusable deploys
  • State - Understand state management
  • Host - Work with individual hosts
  • Inventory - Manage host collections