0
# Core Terraform Operations
1
2
Essential terraform commands that form the core infrastructure lifecycle: initialization, planning, applying changes, and destruction. These operations are the foundation of terraform workflow automation.
3
4
## Capabilities
5
6
### Initialize Working Directory
7
8
Initializes a terraform working directory by downloading providers, modules, and configuring backends. This is typically the first command run in any terraform project.
9
10
```python { .api }
11
def init(self, dir_or_plan: Optional[str] = None, backend_config: Optional[Dict[str, str]] = None,
12
reconfigure: Type[TerraformFlag] = IsFlagged, backend: bool = True, **kwargs) -> CommandOutput:
13
"""
14
Initialize a Terraform working directory.
15
16
Args:
17
dir_or_plan: Path to terraform directory (defaults to working_dir)
18
backend_config: Dictionary of backend configuration options
19
reconfigure: Force reconfiguration of backend (default: IsFlagged)
20
backend: Whether to use backend settings (default: True)
21
**kwargs: Additional terraform options
22
23
Returns:
24
Tuple of (return_code, stdout, stderr)
25
"""
26
```
27
28
Usage examples:
29
30
```python
31
# Basic initialization
32
tf = Terraform(working_dir='/path/to/terraform')
33
return_code, stdout, stderr = tf.init()
34
35
# Initialize with backend configuration
36
return_code, stdout, stderr = tf.init(
37
backend_config={
38
'access_key': 'myaccesskey',
39
'secret_key': 'mysecretkey',
40
'bucket': 'mybucketname'
41
}
42
)
43
44
# Initialize without backend
45
return_code, stdout, stderr = tf.init(backend=False)
46
```
47
48
### Plan Changes
49
50
Creates an execution plan showing what terraform will do when applied. This allows reviewing changes before applying them.
51
52
```python { .api }
53
def plan(self, dir_or_plan: Optional[str] = None, detailed_exitcode: Type[TerraformFlag] = IsFlagged,
54
**kwargs) -> CommandOutput:
55
"""
56
Create a Terraform execution plan.
57
58
Args:
59
dir_or_plan: Path to terraform directory or plan file
60
detailed_exitcode: Return detailed exit codes (default: IsFlagged)
61
**kwargs: Additional terraform options (var, var_file, target, etc.)
62
63
Returns:
64
Tuple of (return_code, stdout, stderr)
65
66
Exit codes with detailed_exitcode=IsFlagged:
67
- 0: No changes
68
- 1: Error
69
- 2: Changes present
70
"""
71
```
72
73
Usage examples:
74
75
```python
76
# Basic plan
77
return_code, stdout, stderr = tf.plan()
78
79
# Plan with variables
80
return_code, stdout, stderr = tf.plan(
81
var={'environment': 'prod', 'instance_count': '3'}
82
)
83
84
# Plan targeting specific resources
85
return_code, stdout, stderr = tf.plan(
86
target=['aws_instance.web', 'aws_security_group.web_sg']
87
)
88
89
# Plan with variable file
90
return_code, stdout, stderr = tf.plan(
91
var_file='prod.tfvars'
92
)
93
```
94
95
### Apply Changes
96
97
Applies the terraform configuration, creating, updating, or deleting resources as specified in the configuration.
98
99
```python { .api }
100
def apply(self, dir_or_plan: Optional[str] = None, input: bool = False, skip_plan: bool = True,
101
no_color: Type[TerraformFlag] = IsFlagged, **kwargs) -> CommandOutput:
102
"""
103
Apply Terraform configuration changes.
104
105
Args:
106
dir_or_plan: Path to terraform directory or plan file
107
input: Enable input prompts for missing variables (default: False)
108
skip_plan: Skip planning phase and apply directly (default: True)
109
no_color: Disable colored output (default: IsFlagged)
110
**kwargs: Additional terraform options
111
112
Returns:
113
Tuple of (return_code, stdout, stderr)
114
"""
115
```
116
117
Usage examples:
118
119
```python
120
# Basic apply (auto-approved)
121
return_code, stdout, stderr = tf.apply()
122
123
# Apply with variables
124
return_code, stdout, stderr = tf.apply(
125
var={'environment': 'staging', 'region': 'us-west-2'}
126
)
127
128
# Apply a specific plan file
129
return_code, stdout, stderr = tf.apply('saved-plan.tfplan')
130
131
# Apply targeting specific resources
132
return_code, stdout, stderr = tf.apply(
133
target=['aws_instance.database']
134
)
135
136
# Apply with custom parallelism
137
return_code, stdout, stderr = tf.apply(parallelism=5)
138
```
139
140
### Destroy Infrastructure
141
142
Destroys all terraform-managed infrastructure or specific targeted resources.
143
144
```python { .api }
145
def destroy(self, dir_or_plan: Optional[str] = None, force: Type[TerraformFlag] = IsFlagged,
146
**kwargs) -> CommandOutput:
147
"""
148
Destroy Terraform-managed infrastructure.
149
150
Args:
151
dir_or_plan: Path to terraform directory
152
force: Skip confirmation prompts (default: IsFlagged)
153
**kwargs: Additional terraform options
154
155
Returns:
156
Tuple of (return_code, stdout, stderr)
157
"""
158
```
159
160
Usage examples:
161
162
```python
163
# Destroy all resources
164
return_code, stdout, stderr = tf.destroy()
165
166
# Destroy specific resources only
167
return_code, stdout, stderr = tf.destroy(
168
target=['aws_instance.temp_server']
169
)
170
171
# Destroy with variables
172
return_code, stdout, stderr = tf.destroy(
173
var={'environment': 'test'}
174
)
175
```
176
177
## Common Options
178
179
All core operations support these common terraform options:
180
181
- **var**: Dictionary of variables (`{'key': 'value'}`)
182
- **var_file**: Path to variable file or list of paths
183
- **target**: List of resource addresses to target
184
- **parallelism**: Number of concurrent operations
185
- **state**: Path to state file
186
- **no_color**: Disable colored output (use `IsFlagged`)
187
- **input**: Enable/disable input prompts (boolean)
188
189
## Error Handling
190
191
All operations raise `TerraformCommandError` on non-zero exit codes unless `raise_on_error=False` is specified:
192
193
```python
194
try:
195
return_code, stdout, stderr = tf.apply()
196
except TerraformCommandError as e:
197
print(f"Apply failed with code {e.returncode}")
198
print(f"Error: {e.err}")
199
```