0
# Core Terraform Objects
1
2
Essential Terraform object types that form the foundation of any Terraform configuration. These classes provide Python representations of Terraform resources, data sources, providers, variables, outputs, modules, and configuration blocks.
3
4
## Capabilities
5
6
### Resource Objects
7
8
Represents Terraform resources - managed infrastructure components that Terraform creates, updates, and destroys.
9
10
```python { .api }
11
class Resource:
12
def __init__(self, type: str, name: str, **kwargs):
13
"""
14
Create a Terraform resource.
15
16
Parameters:
17
- type: str - Terraform resource type (e.g., 'aws_instance', 'aws_s3_bucket')
18
- name: str - Resource name for referencing
19
- **kwargs: Resource-specific configuration attributes
20
21
Example:
22
Resource('aws_instance', 'web_server',
23
instance_type='t3.micro',
24
ami='ami-12345678')
25
"""
26
27
def __getattr__(self, name: str) -> TypedObjectAttr:
28
"""Returns Terraform interpolation syntax for resource attributes.
29
30
Example:
31
web_server.id returns "${aws_instance.web_server.id}"
32
web_server.public_ip returns "${aws_instance.web_server.public_ip}"
33
"""
34
```
35
36
### Data Sources
37
38
Represents Terraform data sources - read-only information about existing infrastructure or external services.
39
40
```python { .api }
41
class Data:
42
def __init__(self, type: str, name: str, **kwargs):
43
"""
44
Create a Terraform data source.
45
46
Parameters:
47
- type: str - Terraform data source type (e.g., 'aws_ami', 'aws_availability_zones')
48
- name: str - Data source name for referencing
49
- **kwargs: Data source-specific filter and configuration attributes
50
51
Example:
52
Data('aws_ami', 'ubuntu',
53
most_recent=True,
54
owners=['099720109477'],
55
filters={'name': 'ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*'})
56
"""
57
58
def __getattr__(self, name: str) -> TypedObjectAttr:
59
"""Returns Terraform interpolation syntax for data source attributes.
60
61
Example:
62
ubuntu_ami.id returns "${data.aws_ami.ubuntu.id}"
63
ubuntu_ami.image_id returns "${data.aws_ami.ubuntu.image_id}"
64
"""
65
```
66
67
### Provider Configuration
68
69
Represents Terraform provider configurations, including support for provider aliases and context management.
70
71
```python { .api }
72
class Provider:
73
def __init__(self, name: str, **kwargs):
74
"""
75
Create a Terraform provider configuration.
76
77
Parameters:
78
- name: str - Provider name (e.g., 'aws', 'google', 'azurerm')
79
- alias: str, optional - Provider alias for multiple configurations
80
- **kwargs: Provider-specific configuration options
81
82
Example:
83
Provider('aws', region='us-west-2', alias='west')
84
"""
85
86
def __enter__(self):
87
"""Context manager entry - resources created within use this provider."""
88
89
def __exit__(self, exc_type, exc_val, exc_tb):
90
"""Context manager exit."""
91
```
92
93
### Variable Declarations
94
95
Represents Terraform input variables that parameterize configurations.
96
97
```python { .api }
98
class Variable:
99
def __init__(self, name: str, **kwargs):
100
"""
101
Create a Terraform variable.
102
103
Parameters:
104
- name: str - Variable name
105
- default: Any, optional - Default value
106
- description: str, optional - Variable description
107
- type: str, optional - Variable type constraint
108
- sensitive: bool, optional - Mark as sensitive
109
- validation: dict, optional - Variable validation rules
110
111
Example:
112
Variable('environment',
113
default='dev',
114
description='Deployment environment',
115
type='string')
116
"""
117
118
def __repr__(self) -> str:
119
"""Returns ${var.name} interpolation syntax when used as string.
120
121
Example:
122
env = Variable('environment')
123
str(env) returns "${var.environment}"
124
"""
125
```
126
127
### Output Values
128
129
Represents Terraform output values that expose information from configurations.
130
131
```python { .api }
132
class Output:
133
def __init__(self, name: str, **kwargs):
134
"""
135
Create a Terraform output.
136
137
Parameters:
138
- name: str - Output name
139
- value: Any - Output value (usually interpolation reference)
140
- description: str, optional - Output description
141
- sensitive: bool, optional - Mark as sensitive
142
143
Example:
144
Output('instance_id',
145
value=web_server.id,
146
description='Web server instance ID')
147
"""
148
```
149
150
### Module Instances
151
152
Represents Terraform module instances that encapsulate reusable infrastructure components.
153
154
```python { .api }
155
class Module:
156
def __init__(self, name: str, **kwargs):
157
"""
158
Create a Terraform module instance.
159
160
Parameters:
161
- name: str - Module instance name
162
- source: str - Module source path or URL
163
- version: str, optional - Module version constraint
164
- **kwargs: Module input variables
165
166
Example:
167
Module('vpc',
168
source='terraform-aws-modules/vpc/aws',
169
version='~> 3.0',
170
cidr='10.0.0.0/16')
171
"""
172
173
def __getattr__(self, name: str) -> str:
174
"""Returns Terraform interpolation syntax for module outputs.
175
176
Example:
177
vpc_module.vpc_id returns "${module.vpc.vpc_id}"
178
vpc_module.subnet_ids returns "${module.vpc.subnet_ids}"
179
"""
180
```
181
182
### Terraform Configuration
183
184
Represents Terraform configuration blocks for backend, required providers, and other settings.
185
186
```python { .api }
187
class Terraform:
188
def __init__(self, **kwargs):
189
"""
190
Create a Terraform configuration block.
191
192
Parameters:
193
- backend: dict, optional - Backend configuration
194
- required_providers: dict, optional - Provider requirements
195
- required_version: str, optional - Terraform version constraint
196
197
Example:
198
Terraform(
199
backend={'s3': {
200
'bucket': 'my-tf-state',
201
'key': 'terraform.tfstate',
202
'region': 'us-west-2'
203
}},
204
required_providers={
205
'aws': {
206
'source': 'hashicorp/aws',
207
'version': '~> 5.0'
208
}
209
}
210
)
211
"""
212
```
213
214
## Usage Examples
215
216
### Basic Resource Creation
217
218
```python
219
from terraformpy import Resource, Variable
220
221
# Create variable
222
instance_type = Variable('instance_type', default='t3.micro')
223
224
# Create resource with interpolation
225
web_server = Resource('aws_instance', 'web',
226
instance_type=instance_type, # Variable used directly
227
ami='ami-12345678',
228
tags={'Name': 'WebServer'}
229
)
230
```
231
232
### Provider Context Management
233
234
```python
235
from terraformpy import Provider, Resource
236
237
# Use provider context
238
with Provider('aws', region='us-west-2', alias='west'):
239
# Resources created here automatically use the west provider
240
Resource('aws_instance', 'west_server', instance_type='t3.micro')
241
242
# Different provider context
243
with Provider('aws', region='us-east-1', alias='east'):
244
Resource('aws_instance', 'east_server', instance_type='t3.micro')
245
```
246
247
### Data Source Usage
248
249
```python
250
from terraformpy import Data, Resource
251
252
# Query existing AMI
253
ubuntu_ami = Data('aws_ami', 'ubuntu',
254
most_recent=True,
255
owners=['099720109477'],
256
filters={'name': 'ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*'}
257
)
258
259
# Use in resource
260
web_server = Resource('aws_instance', 'web',
261
ami=ubuntu_ami.id, # Interpolation: ${data.aws_ami.ubuntu.id}
262
instance_type='t3.micro'
263
)
264
```
265
266
### Module Integration
267
268
```python
269
from terraformpy import Module, Output
270
271
# Create module instance
272
vpc = Module('main_vpc',
273
source='terraform-aws-modules/vpc/aws',
274
version='~> 3.0',
275
276
# Module inputs
277
cidr='10.0.0.0/16',
278
azs=['us-west-2a', 'us-west-2b'],
279
private_subnets=['10.0.1.0/24', '10.0.2.0/24'],
280
public_subnets=['10.0.101.0/24', '10.0.102.0/24'],
281
enable_nat_gateway=True
282
)
283
284
# Reference module outputs
285
Output('vpc_id', value=vpc.vpc_id) # Generates ${module.main_vpc.vpc_id}
286
Output('private_subnets', value=vpc.private_subnets) # Generates ${module.main_vpc.private_subnets}
287
288
## Base Classes
289
290
Core base classes that provide the foundation for all Terraform objects in terraformpy.
291
292
### TFObject
293
294
Root base class for all Terraform objects with global registry and hook system.
295
296
```python { .api }
297
class TFObject:
298
@classmethod
299
def compile() -> dict:
300
"""Compile all registered objects to Terraform configuration dictionary."""
301
302
@classmethod
303
def reset() -> None:
304
"""Clear all registered objects from the global registry."""
305
306
@classmethod
307
def add_hook(object_type: str, hook_function: Callable[[dict], dict]) -> None:
308
"""Add transformation hook for objects of the specified type."""
309
310
def build() -> dict:
311
"""Build the Terraform JSON representation of this object."""
312
```
313
314
### NamedObject
315
316
Base class for Terraform objects with a single name (variables, outputs, providers, modules).
317
318
```python { .api }
319
class NamedObject(TFObject):
320
def __init__(self, _name: str, **kwargs):
321
"""
322
Create a named Terraform object.
323
324
Parameters:
325
- _name: str - Object name
326
- **kwargs: Object-specific attributes
327
"""
328
329
@classmethod
330
def add_hook(cls, object_name: str, hook_function: Callable[[dict], dict]) -> None:
331
"""Add hook for named objects that receives object attributes."""
332
```
333
334
### TypedObject
335
336
Base class for Terraform objects with both type and name (resources, data sources).
337
338
```python { .api }
339
class TypedObject(NamedObject):
340
def __init__(self, _type: str, _name: str, **kwargs):
341
"""
342
Create a typed Terraform object.
343
344
Parameters:
345
- _type: str - Terraform object type (e.g., 'aws_instance', 'aws_ami')
346
- _name: str - Object name for referencing
347
- **kwargs: Object-specific attributes
348
"""
349
350
@classmethod
351
def add_hook(cls, object_type: str, hook_function: Callable[[str, dict], dict]) -> None:
352
"""Add hook for typed objects that receives object ID and attributes."""
353
354
def __getattr__(self, name: str) -> TypedObjectAttr:
355
"""Return Terraform interpolation syntax for accessing attributes."""
356
357
@property
358
def terraform_name(self) -> str:
359
"""Return the full Terraform name (type.name) for interpolation."""
360
```
361
362
### TypedObjectAttr
363
364
String subclass that generates Terraform interpolation syntax for resource/data attributes.
365
366
```python { .api }
367
class TypedObjectAttr(str):
368
def __init__(self, terraform_name: str, attr_name: str):
369
"""
370
Create Terraform interpolation reference.
371
372
Parameters:
373
- terraform_name: str - Full Terraform object name (e.g., 'aws_instance.web')
374
- attr_name: str - Attribute name (e.g., 'id', 'public_ip')
375
376
Returns string like: "${aws_instance.web.id}"
377
"""
378
379
def __getitem__(self, key: str) -> TypedObjectAttr:
380
"""Support array/map indexing: resource.attribute[key]."""
381
382
def __getattr__(self, name: str) -> TypedObjectAttr:
383
"""Support nested attribute access: resource.attribute.nested."""
384
```