0
# Variables and Outputs
1
2
Input variables and output values for parameterizing infrastructure and exposing computed values, enabling flexible and reusable Terraform configurations.
3
4
## Capabilities
5
6
### TerraformVariable Class
7
8
Input variables that parameterize your Terraform configuration, allowing customization without modifying the code.
9
10
```typescript { .api }
11
/**
12
* Terraform input variable for parameterizing configurations
13
*/
14
class TerraformVariable extends TerraformElement {
15
/**
16
* Create a new Terraform variable
17
* @param scope - The parent construct
18
* @param id - Variable identifier
19
* @param config - Variable configuration
20
*/
21
constructor(scope: Construct, id: string, config: TerraformVariableConfig);
22
23
/**
24
* Add a validation rule to the variable
25
* @param validation - Validation configuration
26
*/
27
addValidation(validation: TerraformVariableValidationConfig): void;
28
29
/**
30
* The variable value as a string
31
*/
32
readonly stringValue: string;
33
34
/**
35
* The variable value as a number
36
*/
37
readonly numberValue: number;
38
39
/**
40
* The variable value as a list of strings
41
*/
42
readonly listValue: string[];
43
44
/**
45
* The variable value as a boolean
46
*/
47
readonly booleanValue: IResolvable;
48
49
/**
50
* The raw variable value
51
*/
52
readonly value: any;
53
54
/**
55
* Default value for the variable
56
*/
57
readonly default?: any;
58
59
/**
60
* Description of the variable
61
*/
62
readonly description?: string;
63
64
/**
65
* Type constraint for the variable
66
*/
67
readonly type?: string;
68
69
/**
70
* Whether the variable is sensitive
71
*/
72
readonly sensitive?: boolean;
73
74
/**
75
* Whether the variable can be null
76
*/
77
readonly nullable?: boolean;
78
79
/**
80
* Validation rules for the variable
81
*/
82
readonly validation?: TerraformVariableValidationConfig[];
83
}
84
```
85
86
**Usage Examples:**
87
88
```typescript
89
import { TerraformVariable, VariableType } from "cdktf";
90
91
// Simple string variable
92
const region = new TerraformVariable(this, "region", {
93
type: VariableType.STRING,
94
default: "us-east-1",
95
description: "AWS region for resources"
96
});
97
98
// Number variable with validation
99
const instanceCount = new TerraformVariable(this, "instance_count", {
100
type: VariableType.NUMBER,
101
default: 1,
102
description: "Number of instances to create"
103
});
104
105
instanceCount.addValidation({
106
condition: `var.instance_count >= 1 && var.instance_count <= 10`,
107
errorMessage: "Instance count must be between 1 and 10"
108
});
109
110
// List variable
111
const availabilityZones = new TerraformVariable(this, "availability_zones", {
112
type: VariableType.list(VariableType.STRING),
113
default: ["us-east-1a", "us-east-1b"],
114
description: "List of availability zones"
115
});
116
117
// Object variable
118
const instanceConfig = new TerraformVariable(this, "instance_config", {
119
type: VariableType.object({
120
instance_type: VariableType.STRING,
121
key_name: VariableType.STRING,
122
monitoring: VariableType.BOOL
123
}),
124
default: {
125
instance_type: "t2.micro",
126
key_name: "default",
127
monitoring: false
128
}
129
});
130
131
// Sensitive variable
132
const dbPassword = new TerraformVariable(this, "db_password", {
133
type: VariableType.STRING,
134
description: "Database password",
135
sensitive: true
136
});
137
138
// Using variable values in resources
139
new AwsInstance(this, "web", {
140
ami: "ami-12345678",
141
instanceType: instanceConfig.value.instance_type,
142
availabilityZone: availabilityZones.listValue[0],
143
keyName: instanceConfig.value.key_name,
144
tags: {
145
Environment: region.stringValue,
146
InstanceCount: instanceCount.stringValue
147
}
148
});
149
```
150
151
### TerraformOutput Class
152
153
Output values that expose computed attributes and results from your Terraform configuration.
154
155
```typescript { .api }
156
/**
157
* Terraform output for exposing computed values
158
*/
159
class TerraformOutput extends TerraformElement {
160
/**
161
* Create a new Terraform output
162
* @param scope - The parent construct
163
* @param id - Output identifier
164
* @param config - Output configuration
165
*/
166
constructor(scope: Construct, id: string, config: TerraformOutputConfig);
167
168
/**
169
* The output value
170
*/
171
readonly value: any;
172
173
/**
174
* Description of the output
175
*/
176
readonly description?: string;
177
178
/**
179
* Whether the output is sensitive
180
*/
181
readonly sensitive?: boolean;
182
183
/**
184
* Resources this output depends on
185
*/
186
readonly dependsOn?: ITerraformDependable[];
187
188
/**
189
* Static ID for the output (overrides generated ID)
190
*/
191
readonly staticId?: boolean;
192
193
/**
194
* Check if a construct is a TerraformOutput
195
*/
196
static isTerraformOutput(x: any): x is TerraformOutput;
197
}
198
```
199
200
**Usage Examples:**
201
202
```typescript
203
import { TerraformOutput } from "cdktf";
204
205
class MyStack extends TerraformStack {
206
constructor(scope: Construct, id: string) {
207
super(scope, id);
208
209
const vpc = new AwsVpc(this, "vpc", {
210
cidrBlock: "10.0.0.0/16"
211
});
212
213
const instance = new AwsInstance(this, "web", {
214
ami: "ami-12345678",
215
instanceType: "t2.micro",
216
vpcSecurityGroupIds: [securityGroup.id],
217
subnetId: subnet.id
218
});
219
220
// Simple string output
221
new TerraformOutput(this, "vpc_id", {
222
value: vpc.id,
223
description: "VPC ID"
224
});
225
226
// Sensitive output
227
new TerraformOutput(this, "instance_private_ip", {
228
value: instance.privateIp,
229
description: "Private IP address of the instance",
230
sensitive: true
231
});
232
233
// Complex object output
234
new TerraformOutput(this, "instance_info", {
235
value: {
236
id: instance.id,
237
public_ip: instance.publicIp,
238
private_ip: instance.privateIp,
239
availability_zone: instance.availabilityZone
240
},
241
description: "Complete instance information"
242
});
243
244
// Output with dependencies
245
new TerraformOutput(this, "database_endpoint", {
246
value: database.endpoint,
247
description: "RDS database endpoint",
248
dependsOn: [database]
249
});
250
251
// List output
252
new TerraformOutput(this, "subnet_ids", {
253
value: subnets.map(subnet => subnet.id),
254
description: "List of subnet IDs"
255
});
256
}
257
}
258
```
259
260
### VariableType Class
261
262
Utility class for defining variable type constraints.
263
264
```typescript { .api }
265
/**
266
* Type constraint definitions for Terraform variables
267
*/
268
class VariableType {
269
/**
270
* String type constraint
271
*/
272
static readonly STRING: string;
273
274
/**
275
* Number type constraint
276
*/
277
static readonly NUMBER: string;
278
279
/**
280
* Boolean type constraint
281
*/
282
static readonly BOOL: string;
283
284
/**
285
* Any type constraint (no validation)
286
*/
287
static readonly ANY: string;
288
289
/**
290
* List type constraint
291
*/
292
static readonly LIST: string;
293
294
/**
295
* Map type constraint
296
*/
297
static readonly MAP: string;
298
299
/**
300
* Set type constraint
301
*/
302
static readonly SET: string;
303
304
/**
305
* Create a list type with element type constraint
306
* @param elementType - Type of list elements
307
* @returns List type string
308
*/
309
static list(elementType: string): string;
310
311
/**
312
* Create a map type with element type constraint
313
* @param elementType - Type of map values
314
* @returns Map type string
315
*/
316
static map(elementType: string): string;
317
318
/**
319
* Create a set type with element type constraint
320
* @param elementType - Type of set elements
321
* @returns Set type string
322
*/
323
static set(elementType: string): string;
324
325
/**
326
* Create a tuple type with specified element types
327
* @param elements - Array of element type strings
328
* @returns Tuple type string
329
*/
330
static tuple(...elements: string[]): string;
331
332
/**
333
* Create an object type with specified attribute types
334
* @param attributes - Map of attribute names to types
335
* @returns Object type string
336
*/
337
static object(attributes: {[key: string]: string}): string;
338
339
/**
340
* Create an optional object attribute
341
* @param type - The attribute type
342
* @returns Optional attribute type string
343
*/
344
static optional(type: string): string;
345
}
346
```
347
348
**Usage Examples:**
349
350
```typescript
351
import { TerraformVariable, VariableType } from "cdktf";
352
353
// Basic types
354
const region = new TerraformVariable(this, "region", {
355
type: VariableType.STRING
356
});
357
358
const count = new TerraformVariable(this, "count", {
359
type: VariableType.NUMBER
360
});
361
362
const enabled = new TerraformVariable(this, "enabled", {
363
type: VariableType.BOOL
364
});
365
366
// Collection types
367
const zones = new TerraformVariable(this, "zones", {
368
type: VariableType.list(VariableType.STRING)
369
});
370
371
const tags = new TerraformVariable(this, "tags", {
372
type: VariableType.map(VariableType.STRING)
373
});
374
375
const uniquePorts = new TerraformVariable(this, "ports", {
376
type: VariableType.set(VariableType.NUMBER)
377
});
378
379
// Complex types
380
const serverConfig = new TerraformVariable(this, "server_config", {
381
type: VariableType.object({
382
instance_type: VariableType.STRING,
383
disk_size: VariableType.NUMBER,
384
monitoring: VariableType.BOOL,
385
backup_retention: VariableType.optional(VariableType.NUMBER)
386
})
387
});
388
389
const vpcCidrs = new TerraformVariable(this, "vpc_cidrs", {
390
type: VariableType.tuple(
391
VariableType.STRING, // VPC CIDR
392
VariableType.STRING, // Public subnet CIDR
393
VariableType.STRING // Private subnet CIDR
394
)
395
});
396
```
397
398
## Configuration Interfaces
399
400
```typescript { .api }
401
interface TerraformVariableConfig {
402
/**
403
* Default value for the variable
404
*/
405
readonly default?: any;
406
407
/**
408
* Description of the variable's purpose
409
*/
410
readonly description?: string;
411
412
/**
413
* Type constraint for the variable
414
*/
415
readonly type?: string;
416
417
/**
418
* Whether the variable value is sensitive
419
* @default false
420
*/
421
readonly sensitive?: boolean;
422
423
/**
424
* Whether the variable can be set to null
425
* @default true
426
*/
427
readonly nullable?: boolean;
428
429
/**
430
* Validation rules for the variable
431
*/
432
readonly validation?: TerraformVariableValidationConfig[];
433
}
434
435
interface TerraformVariableValidationConfig {
436
/**
437
* Condition expression that must evaluate to true
438
*/
439
readonly condition: string;
440
441
/**
442
* Error message to show when validation fails
443
*/
444
readonly errorMessage: string;
445
}
446
447
interface TerraformOutputConfig {
448
/**
449
* The value to output (can be a literal, reference, or expression)
450
*/
451
readonly value: any;
452
453
/**
454
* Description of what this output represents
455
*/
456
readonly description?: string;
457
458
/**
459
* Whether the output value is sensitive
460
* @default false
461
*/
462
readonly sensitive?: boolean;
463
464
/**
465
* Explicit dependencies for this output
466
*/
467
readonly dependsOn?: ITerraformDependable[];
468
469
/**
470
* Use a static ID instead of generating one
471
* @default false
472
*/
473
readonly staticId?: boolean;
474
475
/**
476
* Conditions that must be met before creating the output
477
*/
478
readonly precondition?: TerraformCondition[];
479
}
480
```