Skip to main content
Connectors are pyinfra’s abstraction for executing commands on remote hosts. While pyinfra includes connectors for SSH, Docker, and local execution, you can create custom connectors for other connection methods like custom protocols, cloud APIs, or container orchestrators.

Understanding Connectors

Connectors in pyinfra:
  • Establish and manage connections to remote hosts
  • Execute shell commands and return output
  • Transfer files to and from remote hosts
  • Can define custom host data and configuration
  • Are loaded via Python entry points

The BaseConnector Class

All connectors inherit from BaseConnector, defined in src/pyinfra/connectors/base.py:71:

Creating a Basic Connector

Here’s a simple example based on the local connector pattern from src/pyinfra/connectors/local.py:26:

Complete Example: REST API Connector

Here’s a more complete example of a connector that manages resources via a REST API:

Registering Your Connector

Connectors are loaded via Python entry points. Add this to your setup.py or pyproject.toml:

setup.py

pyproject.toml

Helper Utilities

pyinfra provides utilities for common connector tasks:

Command Building

Running Local Processes

Sudo Retry Logic

Connector Data Types

Define typed connector data for better validation:

Testing Your Connector

Create a test script:
Run with your connector:

Best Practices

  1. Error Handling: Always raise ConnectError for connection failures
  2. Logging: Use pyinfra’s logger for consistent output
  3. Type Safety: Use TypedDict for connector data and type hints throughout
  4. Resource Cleanup: Implement disconnect() to clean up connections
  5. Timeout Handling: Respect timeout arguments for all operations
  6. Sudo Support: Use make_unix_command_for_host to handle sudo/su properly
  7. Test Thoroughly: Test with various commands, file operations, and error conditions
  8. Documentation: Document connector usage and configuration options
  9. Connection Pooling: Consider implementing connection reuse for performance
  10. Error Messages: Provide clear, actionable error messages

Next Steps