Skip to main content
The Terraform connector generates pyinfra inventory from Terraform output variables. This enables seamless integration between Terraform infrastructure provisioning and pyinfra configuration management.

Overview

The Terraform connector reads terraform output -json to generate hosts dynamically based on Terraform state.
The Terraform connector is in beta. Report issues on GitHub if you encounter problems.

Requirements

  • Terraform CLI installed and accessible
  • Terraform state with output variables
  • Current directory contains Terraform configuration

Terraform Output Format

The connector uses flattened JSON output from terraform output -json:
Access with:

Basic Usage

List of IPs

Simplest form - list of IP addresses or hostnames:

Named Output

Use specific output variable:

Advanced Usage

Hosts with Data

Pass host-specific data:

AWS Example

Complete AWS infrastructure with Terraform and pyinfra:

Nested Outputs

Access nested output structures:

Default Output Name

If no output name is specified, the connector looks for pyinfra_inventory.value:

SSH Configuration

Set SSH connection details in Terraform outputs:
Available SSH data keys:
  • ssh_hostname - Hostname or IP
  • ssh_user - SSH username
  • ssh_key - Path to private key
  • ssh_password - SSH password (not recommended)
  • ssh_port - SSH port (default: 22)
  • ssh_forward_agent - Enable agent forwarding

Workflow

Typical Terraform + pyinfra workflow:

Multiple Environments

Manage multiple environments with Terraform workspaces:

Error Handling

The connector validates Terraform output:

Testing

Test Terraform outputs before deploying:

Limitations

  • Requires Terraform CLI in PATH
  • Must run from directory with Terraform state
  • Output must be valid JSON
  • Re-reads output on each run (can be slow for large state)

Best Practices

  1. Use descriptive output names
  2. Include necessary SSH data
  3. Add host data for conditional deploys
  4. Use Terraform outputs for dynamic data

Complete Example

Here’s a complete example with Terraform and pyinfra:

Source Reference

Location: src/pyinfra/connectors/terraform.py:30

Key Methods

  • make_names_data() - Generate hosts from Terraform output (line 83)