0
# Resources and Data Sources
1
2
Terraform resource and data source management providing the foundation for infrastructure provisioning with full attribute access, lifecycle controls, and state management.
3
4
## Capabilities
5
6
### TerraformResource Class
7
8
Represents a Terraform resource that creates and manages infrastructure components.
9
10
```typescript { .api }
11
/**
12
* Represents a Terraform resource that creates and manages infrastructure
13
*/
14
class TerraformResource extends TerraformElement {
15
/**
16
* Create a new Terraform resource
17
* @param scope - The parent construct
18
* @param id - Resource identifier
19
* @param config - Resource configuration
20
*/
21
constructor(scope: Construct, id: string, config: TerraformResourceConfig);
22
23
/**
24
* Get a string attribute from the resource
25
* @param terraformAttribute - Name of the attribute
26
* @returns String value of the attribute
27
*/
28
getStringAttribute(terraformAttribute: string): string;
29
30
/**
31
* Get a number attribute from the resource
32
* @param terraformAttribute - Name of the attribute
33
* @returns Numeric value of the attribute
34
*/
35
getNumberAttribute(terraformAttribute: string): number;
36
37
/**
38
* Get a list attribute from the resource
39
* @param terraformAttribute - Name of the attribute
40
* @returns Array of string values
41
*/
42
getListAttribute(terraformAttribute: string): string[];
43
44
/**
45
* Get a boolean attribute from the resource
46
* @param terraformAttribute - Name of the attribute
47
* @returns Boolean value as resolvable
48
*/
49
getBooleanAttribute(terraformAttribute: string): IResolvable;
50
51
/**
52
* Get a number list attribute from the resource
53
* @param terraformAttribute - Name of the attribute
54
* @returns Array of numeric values
55
*/
56
getNumberListAttribute(terraformAttribute: string): number[];
57
58
/**
59
* Get a string map attribute from the resource
60
* @param terraformAttribute - Name of the attribute
61
* @returns Map of string values
62
*/
63
getStringMapAttribute(terraformAttribute: string): {[key: string]: string};
64
65
/**
66
* Get a number map attribute from the resource
67
* @param terraformAttribute - Name of the attribute
68
* @returns Map of numeric values
69
*/
70
getNumberMapAttribute(terraformAttribute: string): {[key: string]: number};
71
72
/**
73
* Get a boolean map attribute from the resource
74
* @param terraformAttribute - Name of the attribute
75
* @returns Map of boolean values
76
*/
77
getBooleanMapAttribute(terraformAttribute: string): {[key: string]: boolean};
78
79
/**
80
* Get any map attribute from the resource
81
* @param terraformAttribute - Name of the attribute
82
* @returns Map of any values
83
*/
84
getAnyMapAttribute(terraformAttribute: string): {[key: string]: any};
85
86
/**
87
* Create an interpolation for an attribute
88
* @param terraformAttribute - Name of the attribute
89
* @returns Resolvable interpolation
90
*/
91
interpolationForAttribute(terraformAttribute: string): IResolvable;
92
93
/**
94
* Import an existing resource into Terraform state
95
* @param id - The ID of the existing resource
96
* @param provider - Optional provider instance
97
*/
98
importFrom(id: string, provider?: TerraformProvider): void;
99
100
/**
101
* Move this resource to a new location in the configuration
102
* @param moveTarget - The move target
103
* @param index - Optional index for resources with for_each
104
*/
105
moveTo(moveTarget: string, index?: string | number): void;
106
107
/**
108
* Move this resource to a resource with the given ID
109
* @param id - The target resource ID
110
*/
111
moveToId(id: string): void;
112
113
/**
114
* Move the resource corresponding to "id" to this resource
115
* @param id - Full id of resource being moved from
116
*/
117
moveFromId(id: string): void;
118
119
/**
120
* Add a target for resource moves
121
* @param moveTarget - The move target identifier
122
*/
123
addMoveTarget(moveTarget: string): void;
124
125
/**
126
* Check if this resource has resource move operations
127
* @returns True if resource has move operations
128
*/
129
hasResourceMove(): boolean;
130
131
/**
132
* Check if a construct is a TerraformResource
133
*/
134
static isTerraformResource(x: any): x is TerraformResource;
135
}
136
```
137
138
**Usage Examples:**
139
140
```typescript
141
import { TerraformResource } from "cdktf";
142
import { Construct } from "constructs";
143
144
// Custom resource class extending TerraformResource
145
class AwsInstance extends TerraformResource {
146
constructor(scope: Construct, id: string, config: AwsInstanceConfig) {
147
super(scope, id, {
148
terraformResourceType: "aws_instance",
149
terraformGeneratorMetadata: {
150
providerName: "aws"
151
},
152
...config
153
});
154
}
155
156
// Attribute getters
157
get id(): string {
158
return this.getStringAttribute("id");
159
}
160
161
get publicIp(): string {
162
return this.getStringAttribute("public_ip");
163
}
164
165
get tags(): {[key: string]: string} {
166
return this.getStringMapAttribute("tags");
167
}
168
}
169
170
// Using the resource
171
const instance = new AwsInstance(this, "web-server", {
172
ami: "ami-12345678",
173
instanceType: "t2.micro",
174
tags: {
175
Name: "Web Server",
176
Environment: "production"
177
}
178
});
179
180
// Access computed attributes
181
const instanceId = instance.id;
182
const publicIp = instance.publicIp;
183
184
// Import existing resource
185
instance.importFrom("i-1234567890abcdef0");
186
```
187
188
### TerraformDataSource Class
189
190
Represents a Terraform data source that reads information about existing infrastructure.
191
192
```typescript { .api }
193
/**
194
* Represents a Terraform data source for reading existing infrastructure
195
*/
196
class TerraformDataSource extends TerraformElement {
197
/**
198
* Create a new Terraform data source
199
* @param scope - The parent construct
200
* @param id - Data source identifier
201
* @param config - Data source configuration
202
*/
203
constructor(scope: Construct, id: string, config: TerraformResourceConfig);
204
205
/**
206
* Get a string attribute from the data source
207
* @param terraformAttribute - Name of the attribute
208
* @returns String value of the attribute
209
*/
210
getStringAttribute(terraformAttribute: string): string;
211
212
/**
213
* Get a number attribute from the data source
214
* @param terraformAttribute - Name of the attribute
215
* @returns Numeric value of the attribute
216
*/
217
getNumberAttribute(terraformAttribute: string): number;
218
219
/**
220
* Get a list attribute from the data source
221
* @param terraformAttribute - Name of the attribute
222
* @returns Array of string values
223
*/
224
getListAttribute(terraformAttribute: string): string[];
225
226
/**
227
* Get a boolean attribute from the data source
228
* @param terraformAttribute - Name of the attribute
229
* @returns Boolean value as resolvable
230
*/
231
getBooleanAttribute(terraformAttribute: string): IResolvable;
232
233
/**
234
* All other attribute getter methods same as TerraformResource
235
*/
236
237
/**
238
* Create an interpolation for an attribute
239
* @param terraformAttribute - Name of the attribute
240
* @returns Resolvable interpolation
241
*/
242
interpolationForAttribute(terraformAttribute: string): IResolvable;
243
244
/**
245
* Check if a construct is a TerraformDataSource
246
*/
247
static isTerraformDataSource(x: any): x is TerraformDataSource;
248
}
249
```
250
251
**Usage Examples:**
252
253
```typescript
254
import { TerraformDataSource } from "cdktf";
255
import { Construct } from "constructs";
256
257
// Custom data source class
258
class DataAwsAmi extends TerraformDataSource {
259
constructor(scope: Construct, id: string, config: DataAwsAmiConfig) {
260
super(scope, id, {
261
terraformResourceType: "aws_ami",
262
terraformGeneratorMetadata: {
263
providerName: "aws"
264
},
265
...config
266
});
267
}
268
269
get id(): string {
270
return this.getStringAttribute("id");
271
}
272
273
get name(): string {
274
return this.getStringAttribute("name");
275
}
276
277
get ownerId(): string {
278
return this.getStringAttribute("owner_id");
279
}
280
}
281
282
// Using the data source
283
const ubuntu = new DataAwsAmi(this, "ubuntu", {
284
mostRecent: true,
285
owners: ["099720109477"], // Canonical
286
filters: [{
287
name: "name",
288
values: ["ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*"]
289
}]
290
});
291
292
// Use data source output in resources
293
const instance = new AwsInstance(this, "server", {
294
ami: ubuntu.id,
295
instanceType: "t2.micro"
296
});
297
```
298
299
### ImportableResource Class
300
301
Enhanced resource class with built-in import capabilities for managing existing infrastructure.
302
303
```typescript { .api }
304
/**
305
* Enhanced resource with import capabilities
306
*/
307
class ImportableResource extends TerraformResource {
308
/**
309
* Import configuration for the resource
310
*/
311
readonly importId?: string;
312
313
/**
314
* Generate import statements for this resource
315
* @returns Import configuration object
316
*/
317
generateImportStatements(): {[key: string]: string};
318
}
319
```
320
321
## Configuration Interfaces
322
323
```typescript { .api }
324
interface TerraformResourceConfig {
325
/**
326
* The Terraform resource type (e.g., "aws_instance")
327
*/
328
readonly terraformResourceType: string;
329
330
/**
331
* Provider metadata for code generation
332
*/
333
readonly terraformGeneratorMetadata?: TerraformProviderGeneratorMetadata;
334
335
/**
336
* The provider instance to use for this resource
337
*/
338
readonly provider?: TerraformProvider;
339
340
/**
341
* Resources this resource depends on
342
*/
343
readonly dependsOn?: ITerraformDependable[];
344
345
/**
346
* Number of resources to create
347
*/
348
readonly count?: number | TerraformCount;
349
350
/**
351
* Iterator for creating multiple similar resources
352
*/
353
readonly forEach?: ITerraformIterator;
354
355
/**
356
* Lifecycle configuration for the resource
357
*/
358
readonly lifecycle?: TerraformResourceLifecycle;
359
360
/**
361
* Provisioners to run when creating/destroying the resource
362
*/
363
readonly provisioners?: (FileProvisioner | LocalExecProvisioner | RemoteExecProvisioner)[];
364
365
/**
366
* Connection configuration for provisioners
367
*/
368
readonly connection?: SSHProvisionerConnection | WinrmProvisionerConnection;
369
}
370
371
interface TerraformResourceLifecycle {
372
/**
373
* Prevent destruction of this resource
374
* @default false
375
*/
376
readonly preventDestroy?: boolean;
377
378
/**
379
* Create replacement resource before destroying the original
380
* @default false
381
*/
382
readonly createBeforeDestroy?: boolean;
383
384
/**
385
* Ignore changes to specified attributes
386
*/
387
readonly ignoreChanges?: string[] | "all";
388
389
/**
390
* Replace resource when any of these attributes change
391
*/
392
readonly replaceTriggeredBy?: any[];
393
394
/**
395
* Preconditions that must be met before resource operations
396
*/
397
readonly precondition?: TerraformCondition[];
398
399
/**
400
* Postconditions that must be met after resource operations
401
*/
402
readonly postcondition?: TerraformCondition[];
403
}
404
405
interface TerraformCondition {
406
/**
407
* Condition expression that must evaluate to true
408
*/
409
readonly condition: any;
410
411
/**
412
* Error message to display if condition fails
413
*/
414
readonly errorMessage: string;
415
}
416
```