0
# Python Terraform
1
2
A Python wrapper for HashiCorp's Terraform command-line tool that enables developers to execute Terraform commands programmatically within Python applications. This library provides a comprehensive interface that mirrors Terraform's CLI functionality, supporting all standard commands with proper argument handling and Python-friendly option conversion.
3
4
## Package Information
5
6
- **Package Name**: python-terraform
7
- **Language**: Python
8
- **Installation**: `pip install python-terraform`
9
- **Repository**: https://github.com/beelit94/python-terraform
10
11
## Core Imports
12
13
```python
14
from python_terraform import Terraform, IsFlagged, IsNotFlagged
15
```
16
17
For all exports including state management and error handling:
18
19
```python
20
from python_terraform import (
21
Terraform,
22
Tfstate,
23
TerraformCommandError,
24
VariableFiles,
25
IsFlagged,
26
IsNotFlagged
27
)
28
```
29
30
## Basic Usage
31
32
```python
33
from python_terraform import Terraform, IsFlagged
34
35
# Initialize terraform wrapper
36
tf = Terraform(working_dir='/path/to/terraform/project')
37
38
# Initialize terraform project
39
return_code, stdout, stderr = tf.init()
40
41
# Plan the changes
42
return_code, stdout, stderr = tf.plan()
43
44
# Apply the changes
45
return_code, stdout, stderr = tf.apply()
46
47
# Check outputs
48
outputs = tf.output()
49
print(outputs)
50
51
# Destroy infrastructure when done
52
return_code, stdout, stderr = tf.destroy()
53
54
# Using as context manager (automatically cleans up temp files)
55
with Terraform(working_dir='/path/to/terraform/project') as tf:
56
tf.init()
57
tf.apply()
58
```
59
60
## Architecture
61
62
The library follows a straightforward design centered around the main `Terraform` class:
63
64
- **Terraform**: Main wrapper class that provides methods for all terraform commands
65
- **Command Execution**: All terraform commands return a tuple of (return_code, stdout, stderr)
66
- **Option Handling**: Converts Python-style options (underscores) to terraform CLI flags (dashes)
67
- **Flag System**: Uses `IsFlagged`/`IsNotFlagged` sentinel values for boolean command-line flags
68
- **State Management**: Automatically reads and parses terraform state files after successful operations
69
- **Variable Files**: Manages temporary `.tfvars.json` files for complex variable passing
70
71
## Capabilities
72
73
### Core Terraform Operations
74
75
Essential terraform commands including init, plan, apply, and destroy. These form the core infrastructure lifecycle management functionality.
76
77
```python { .api }
78
def init(self, dir_or_plan: Optional[str] = None, backend_config: Optional[Dict[str, str]] = None,
79
reconfigure: Type[TerraformFlag] = IsFlagged, backend: bool = True, **kwargs) -> CommandOutput
80
def plan(self, dir_or_plan: Optional[str] = None, detailed_exitcode: Type[TerraformFlag] = IsFlagged,
81
**kwargs) -> CommandOutput
82
def apply(self, dir_or_plan: Optional[str] = None, input: bool = False, skip_plan: bool = True,
83
no_color: Type[TerraformFlag] = IsFlagged, **kwargs) -> CommandOutput
84
def destroy(self, dir_or_plan: Optional[str] = None, force: Type[TerraformFlag] = IsFlagged,
85
**kwargs) -> CommandOutput
86
```
87
88
[Core Operations](./core-operations.md)
89
90
### Workspace Management
91
92
Terraform workspace operations for managing multiple environments and configurations within the same terraform project.
93
94
```python { .api }
95
def set_workspace(self, workspace: str, *args, **kwargs) -> CommandOutput
96
def create_workspace(self, workspace: str, *args, **kwargs) -> CommandOutput
97
def delete_workspace(self, workspace: str, *args, **kwargs) -> CommandOutput
98
def show_workspace(self, **kwargs) -> CommandOutput
99
```
100
101
[Workspace Management](./workspace-management.md)
102
103
### Command Interface & Utilities
104
105
Generic command execution interface and utility functions for building terraform commands and managing execution.
106
107
```python { .api }
108
def cmd(self, cmd: str, *args, capture_output: Union[bool, str] = True,
109
raise_on_error: bool = True, synchronous: bool = True, **kwargs) -> CommandOutput
110
def generate_cmd_string(self, cmd: str, *args, **kwargs) -> List[str]
111
def output(self, *args, capture_output: bool = True, **kwargs) -> Union[None, str, Dict[str, str], Dict[str, Dict[str, str]]]
112
```
113
114
[Command Interface](./command-interface.md)
115
116
### State File Management
117
118
Operations for reading and managing terraform state files, including parsing state data and accessing resource information.
119
120
```python { .api }
121
def read_state_file(self, file_path: Optional[str] = None) -> None
122
```
123
124
State file parsing through the `Tfstate` class:
125
126
```python { .api }
127
@staticmethod
128
def load_file(file_path: str) -> Tfstate
129
```
130
131
[State Management](./state-management.md)
132
133
## Terraform Class
134
135
The main `Terraform` class constructor accepts several parameters for configuring default behavior:
136
137
```python { .api }
138
class Terraform:
139
def __init__(
140
self,
141
working_dir: Optional[str] = None,
142
targets: Optional[Sequence[str]] = None,
143
state: Optional[str] = None,
144
variables: Optional[Dict[str, str]] = None,
145
parallelism: Optional[str] = None,
146
var_file: Optional[str] = None,
147
terraform_bin_path: Optional[str] = None,
148
is_env_vars_included: bool = True,
149
):
150
"""
151
Initialize Terraform wrapper.
152
153
Args:
154
working_dir: Working directory for terraform operations
155
targets: Default target resources for apply/destroy/plan
156
state: Path to state file relative to working directory
157
variables: Default variables for terraform commands
158
parallelism: Default parallelism value for operations
159
var_file: Default variable file path(s)
160
terraform_bin_path: Path to terraform binary (default: "terraform")
161
is_env_vars_included: Include environment variables in command execution
162
"""
163
164
def __exit__(self, exc_type, exc_value, traceback) -> None:
165
"""Context manager exit - cleans up temporary variable files"""
166
```
167
168
## Types
169
170
```python { .api }
171
# Command output tuple type
172
CommandOutput = Tuple[Optional[int], Optional[str], Optional[str]]
173
174
# Flag classes for terraform boolean options
175
class TerraformFlag:
176
"""Base class for terraform flag values"""
177
178
class IsFlagged(TerraformFlag):
179
"""Sentinel class indicating a flag should be enabled"""
180
181
class IsNotFlagged(TerraformFlag):
182
"""Sentinel class indicating a flag should be disabled"""
183
184
# Custom exception for terraform command failures
185
class TerraformCommandError(subprocess.CalledProcessError):
186
def __init__(self, ret_code: int, cmd: str, out: Optional[str], err: Optional[str]): ...
187
out: Optional[str]
188
err: Optional[str]
189
190
# Variable file manager for complex variable passing
191
class VariableFiles:
192
def __init__(self): ...
193
def create(self, variables: Dict[str, str]) -> str:
194
"""Create temporary .tfvars.json file and return filename"""
195
def clean_up(self) -> None:
196
"""Remove all created temporary files"""
197
198
# Module constants
199
COMMAND_WITH_SUBCOMMANDS = {"workspace"} # Commands that require subcommand handling
200
```
201
202
## Error Handling
203
204
By default, terraform commands that return non-zero exit codes will raise a `TerraformCommandError` exception. This can be disabled by passing `raise_on_error=False` to any command method.
205
206
```python
207
try:
208
return_code, stdout, stderr = tf.apply()
209
except TerraformCommandError as e:
210
print(f"Terraform command failed with return code {e.returncode}")
211
print(f"Error output: {e.err}")
212
```