API Reference¶
The pyinfra API is designed to be used as follows:
- Create the state we are going to operate on, which consists of:
- An inventory
pyinfra.api.Inventorycontaining hostspyinfra.api.Host, plus any data - A config
pyinfra.api.Configfor global flag - A state
pyinfra.api.Statethat combines the inventory & config
- An inventory
- Now that state is setup, we define operations:
pyinfra.api.operation.add_oppyinfra.api.add_deploy
- Now that's done, we execute it:
pyinfra.api.operations.run_ops
Currently the best example of this in action is in pyinfra's own main.py.
Core API¶
pyinfra.api
¶
arguments
¶
all_global_arguments
¶
Return all global arguments and their types.
pop_global_arguments
¶
pop_global_arguments(
state: State, host: Host, kwargs: dict[str, Any]
) -> tuple[AllArguments, list[str]]
Pop and return operation global keyword arguments, in preferred order:
- From the current context (a direct @operator or @deploy function being called)
- From any current @deploy context (deploy kwargs)
- From the host data variables
- From the config variables
command
¶
make_formatted_string_command
¶
Helper function that takes a shell command or script as a string, splits it
using shlex.split and then formats each bit, returning a StringCommand
instance with each bit.
Useful to enable string formatted commands/scripts, for example:
.. code:: python
curl_command = make_formatted_string_command(
'curl -sSLf {0} -o {1}',
QuoteString(src),
QuoteString(dest),
)
config
¶
Config
¶
Bases: ConfigDefaults
The default/base configuration options for a pyinfra deploy.
connect
¶
connect_all
¶
Connect to all the configured servers in parallel. Reads/writes state.inventory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
``pyinfra.api.State`` obj
|
the state containing an inventory to connect to |
required |
disconnect_all
¶
Disconnect from all of the configured servers in parallel. Reads/writes state.inventory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
``pyinfra.api.State`` obj
|
the state containing an inventory to connect to |
required |
deploy
¶
Deploys come in two forms: on-disk, eg deploy.py, and @deploy wrapped functions. The latter enable re-usable (across CLI and API based execution) pyinfra extension creation (eg pyinfra-openstack).
add_deploy
¶
Prepare & add an deploy to pyinfra.state by executing it on all hosts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
``pyinfra.api.State`` obj
|
the deploy state to add the operation |
required |
deploy_func
|
function
|
the operation function from one of the modules, |
required |
args/kwargs
|
passed to the operation function |
required |
deploy
¶
deploy(
name: str | None = None,
data_defaults: dict | None = None,
) -> Callable[[Callable[P, Any]], PyinfraOperation[P]]
Decorator that takes a deploy function (normally from a pyinfra_* package) and wraps any operations called inside with any deploy-wide kwargs/data.
exceptions
¶
ConnectError
¶
Bases: PyinfraError
Exception raised when connecting fails.
FactError
¶
Bases: PyinfraError
Exception raised during fact gathering staging if a fact is unable to generate output/change state.
FactTypeError
¶
FactValueError
¶
Bases: FactError, ValueError
Exception raised when a fact is passed invalid argument values.
FactProcessError
¶
Bases: FactError, RuntimeError
Exception raised when the data gathered for a fact cannot be processed.
OperationError
¶
Bases: PyinfraError
Exception raised during fact gathering staging if an operation is unable to generate output/change state.
OperationTypeError
¶
Bases: OperationError, TypeError
Exception raised when an operation is passed invalid argument types.
OperationValueError
¶
Bases: OperationError, ValueError
Exception raised when an operation is passed invalid argument values.
NestedOperationError
¶
Bases: OperationError
Exception raised when a nested (immediately executed) operation fails.
FactNotCollected
¶
Bases: FactError
Base exception raised when a fact could not be collected (e.g. binary absent on the remote host, or the fact was skipped by a condition).
MissingCommandError
¶
Bases: FactNotCollected
Exception raised when requires_command specifies a binary that is
not present on the remote host. The fact returns its default() value
instead of raising, unless explicitly configured otherwise.
FactPreconditionError
¶
Bases: FactNotCollected
Exception raised when a fact's check_preconditions() returns a reason string
(e.g. a kernel module is not loaded). Like MissingCommandError, this is
silenced during the prepare phase and re-raised during execute.
DeployError
¶
Bases: PyinfraError
User exception for raising in deploys or sub deploys.
InventoryError
¶
Bases: PyinfraError
Exception raised for inventory related errors.
NoConnectorError
¶
Bases: PyinfraError, ValueError
Raised when a requested connector is missing.
NoHostError
¶
Bases: PyinfraError, KeyError
Raised when an inventory is missing a host.
NoGroupError
¶
Bases: PyinfraError, KeyError
Raised when an inventory is missing a group.
ConnectorDataTypeError
¶
Bases: PyinfraError, TypeError
Raised when host connector data has invalid types.
ArgumentTypeError
¶
Bases: PyinfraError, TypeError
Raised when global arguments are passed with invalid types.
facts
¶
The pyinfra facts API. Facts enable pyinfra to collect remote server state which is used to "diff" with the desired state, producing the final commands required for a deploy.
Note that the facts API does not use the global currently in context host so it's possible to call facts on hosts out of context (ie give me the IP of this other host B while I operate on this host A).
FactBase
¶
Bases: Generic[T]
requires_command
¶
Return the binary name that must exist on the remote host for this fact to run.
If the binary is absent the fact returns its default() value silently.
check_preconditions
¶
Check that this fact's prerequisites are satisfied before running.
Override this method to call host.get_fact(...) and return:
None(or no return) — all prerequisites satisfied, proceed normally"reason message"— prerequisite not satisfied with explanation
The framework handles raising FactPreconditionError and phase-awareness
automatically; fact authors never need to import exception classes.
hiddenvalue
¶
HiddenValue
¶
A class to contain a hidden value To retrieve the real value use .unmask()
host
¶
Host
¶
Represents a target host. Thin class that links up to facts and host/group data.
deploy
¶
Wraps a group of operations as a deploy, this should not be used
directly, instead use pyinfra.api.deploy.deploy.
get_temp_filename
¶
get_temp_filename(
hash_key: str | None = None,
hash_filename: bool = True,
*,
temp_directory: str | None = None,
)
Generate a temporary filename for this deploy.
connect
¶
Connect to the host using it's configured connector.
run_shell_command
¶
Low level method to execute a shell command on the host via it's configured connector.
put_file
¶
Low level method to upload a file to the host via it's configured connector.
get_file
¶
Low level method to download a file from the host via it's configured connector.
inventory
¶
Inventory
¶
Represents a collection of target hosts. Stores and provides access to group data, host data and default data for these hosts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
names_data
|
tuple of |
required | |
override_data
|
dictionary of data overrides |
None
|
|
ssh_*
|
deprecated, use |
required | |
winrm_*
|
deprecated, use |
required | |
**groups
|
map of group name -> |
{}
|
metadata
¶
Support parsing pyinfra-metadata.toml
Currently just parses plugins and their metadata.
operation
¶
Operations are the core of pyinfra. The @operation wrapper intercepts calls
to the function and instead diff against the remote server, outputting commands
to the deploy state. This is then run later by pyinfra's __main__ or the
:doc:./pyinfra.api.operations module.
OperationMeta
¶
add_op
¶
Prepare & add an operation to pyinfra.state by executing it on all hosts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
``pyinfra.api.State`` obj
|
the deploy state to add the operation |
required |
to op_func
|
function
|
the operation function from one of the modules, |
required |
args/kwargs
|
passed to the operation function |
required |
operation
¶
operation(
is_idempotent: bool = True,
idempotent_notice: str | None = None,
is_deprecated: bool = False,
deprecated_for: str | None = None,
_set_in_op: bool = True,
) -> Callable[
[Callable[P, Generator]], PyinfraOperation[P]
]
Decorator that takes a simple module function and turn it into the internal operation representation that consists of a list of commands + options (sudo, (sudo|su)_user, env).
operations
¶
run_ops
¶
Runs all operations across all servers in a configurable manner.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
``pyinfra.api.State`` obj
|
the deploy state to execute |
required |
serial
|
boolean
|
whether to run operations host by host |
False
|
no_wait
|
boolean
|
whether to wait for all hosts between operations |
False
|
output
¶
Pluggable output formatting for pyinfra.
Provides format_text and echo functions that default to plain-text
no-ops, allowing the API layer to work without any CLI dependency. The CLI
layer replaces them at startup via set_formatter and set_echo.
format_text
¶
Format text with optional styling (color, bold, etc.).
Mirrors click.style signature. Accepts positional fg argument
for compatibility with click.style("text", "red").
echo
¶
Echo a message. Mirrors click.echo signature.
set_formatter
¶
Replace the default formatter (e.g. with click.style).
set_echo
¶
Replace the default echo function (e.g. with click.echo).
is_output_active
¶
Return True if a non-default echo function has been installed.
state
¶
State
¶
State(
inventory: Inventory | None = None,
config: Config | None = None,
check_for_changes: bool = True,
**kwargs,
)
Manages state for a pyinfra deploy.
Initializes the state, the main Pyinfra
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inventory
|
Optional[Inventory]
|
The inventory. Defaults to None. |
None
|
config
|
Optional[Config]
|
The config object. Defaults to None. |
None
|
util
¶
get_file_io
¶
Given either a filename or an existing IO object, this context processor will open and close filenames, and leave IO objects alone.
get_template
¶
get_template(
filename_or_io: str | IO,
jinja_env_kwargs: dict[str, Any] | None = None,
) -> Template
Gets a jinja2 Template object for the input filename or string, with caching
based on the filename of the template, or the SHA1 of the input string.
make_hash
¶
Make a hash from an arbitrary nested dictionary, list, tuple or set, used to generate ID's for operations based on their name & arguments.
get_path_permissions_mode
¶
Get the permissions (bits) of a path as an integer.