Skip to main content
The Host class represents a single target host and provides access to facts, data, and connector methods for interacting with that host.

Host Class

A Host object is created automatically by pyinfra when building the inventory. You typically access hosts through the inventory or the current context.

Properties

str
The hostname or identifier for this host.
list[str]
List of group names this host belongs to.
HostData
Access to host data with waterfall lookup (override > host > group > global > deploy).
Inventory
Reference to the parent inventory.
State
Reference to the current state object.
BaseConnector
The connector instance for this host.
bool
Whether the host is currently connected.
bool
Whether currently inside an operation function.
bool
Whether currently inside a deploy function.

Host Data

Access host data with waterfall lookup:
Data lookup order:
  1. Deploy data (from @deploy decorator)
  2. Override data (from inventory)
  3. Host-specific data
  4. Group data
  5. Global inventory data

Facts

Retrieve information about the host using facts:

get_fact Method

Connector Methods

The Host class provides direct access to connector methods:

connect()

Connect to the host:
str
Optional reason for connection (shown in logs).
bool
default:true
Whether to display connection errors.
bool
default:false
Whether to raise exceptions on connection failure.

disconnect()

Disconnect from the host:

run_shell_command()

Execute a shell command on the host:

put_file()

Upload a file to the host:

get_file()

Download a file from the host:

rsync()

Sync files using rsync (if supported by connector):

Logging

Log messages with the host prefix:

Noop Operations

Log when operations would do nothing:

Conditional Execution

Use host.when() for conditional operations:

Loop Helper

Loop over iterables while tracking position:
The loop position is used internally for operation ordering.

Temporary Files

Generate temporary file paths:

Complete Example

Here’s a comprehensive example using the Host API:

Source Reference

Location: src/pyinfra/api/host.py:103

Key Methods

  • __init__() - Initialize host (line 147)
  • get_fact() - Retrieve facts (line 366)
  • connect() - Connect to host (line 379)
  • disconnect() - Disconnect from host (line 417)
  • run_shell_command() - Execute commands (line 434)
  • put_file() - Upload files (line 441)
  • get_file() - Download files (line 449)
  • loop() - Loop helper (line 140)
  • when() - Conditional execution (line 247)