0
# Terraform Functions
1
2
Comprehensive access to Terraform's built-in functions for expressions, computations, and data transformations within CDKTF applications.
3
4
## Capabilities
5
6
### Fn Class
7
8
Static utilities providing access to all Terraform built-in functions for use in expressions and configurations.
9
10
```typescript { .api }
11
/**
12
* Terraform built-in function utilities
13
*/
14
class Fn {
15
/**
16
* Generate a bcrypt hash of the given string with optional cost
17
* @param str - String to hash
18
* @param cost - Optional cost parameter (4-31)
19
* @returns Bcrypt hash string
20
*/
21
static bcrypt(str: string, cost?: number): string;
22
23
/**
24
* Conditional expression (ternary operator)
25
* @param condition - Condition to evaluate
26
* @param trueValue - Value if condition is true
27
* @param falseValue - Value if condition is false
28
* @returns Conditional result
29
*/
30
static conditional(condition: any, trueValue: any, falseValue: any): any;
31
32
/**
33
* Look up a value in a map with optional default
34
* @param inputMap - Map to search in
35
* @param key - Key to look up
36
* @param defaultValue - Default value if key not found
37
* @returns Looked up value
38
*/
39
static lookup(inputMap: any, key: string, defaultValue?: any): any;
40
41
/**
42
* Nested lookup in a map using a path array
43
* @param inputMap - Map to search in
44
* @param path - Array of keys for nested lookup
45
* @returns Nested value
46
*/
47
static lookupNested(inputMap: any, path: any[]): any;
48
49
/**
50
* Join a list of strings with a separator
51
* @param separator - String to use as separator
52
* @param list - List of strings to join
53
* @returns Joined string
54
*/
55
static join(separator: string, list: string[]): string;
56
57
/**
58
* Create a range of numbers
59
* @param start - Starting number
60
* @param limit - Ending number (exclusive)
61
* @param step - Step increment
62
* @returns Array of numbers
63
*/
64
static range(start: number, limit: number, step?: number): number[];
65
66
/**
67
* Create a raw string that won't be processed as an expression
68
* @param str - Raw string value
69
* @returns Raw string
70
*/
71
static rawString(str: string): string;
72
73
// String Functions
74
/**
75
* Convert string to lowercase
76
* @param str - Input string
77
* @returns Lowercase string
78
*/
79
static lower(str: string): string;
80
81
/**
82
* Convert string to uppercase
83
* @param str - Input string
84
* @returns Uppercase string
85
*/
86
static upper(str: string): string;
87
88
/**
89
* Get the length of a string, list, or map
90
* @param value - Value to measure
91
* @returns Length as number
92
*/
93
static length(value: any): number;
94
95
/**
96
* Extract substring from a string
97
* @param str - Source string
98
* @param offset - Starting position
99
* @param length - Number of characters
100
* @returns Substring
101
*/
102
static substr(str: string, offset: number, length: number): string;
103
104
/**
105
* Replace occurrences of a substring
106
* @param str - Source string
107
* @param substring - Substring to replace
108
* @param replacement - Replacement string
109
* @returns Modified string
110
*/
111
static replace(str: string, substring: string, replacement: string): string;
112
113
/**
114
* Trim whitespace from string
115
* @param str - Input string
116
* @returns Trimmed string
117
*/
118
static trim(str: string): string;
119
120
/**
121
* Split string into list by separator
122
* @param separator - Character to split on
123
* @param str - String to split
124
* @returns List of string parts
125
*/
126
static split(separator: string, str: string): string[];
127
128
// Collection Functions
129
/**
130
* Get keys from a map
131
* @param inputMap - Input map
132
* @returns List of keys
133
*/
134
static keys(inputMap: any): string[];
135
136
/**
137
* Get values from a map
138
* @param inputMap - Input map
139
* @returns List of values
140
*/
141
static values(inputMap: any): any[];
142
143
/**
144
* Create a map from lists of keys and values
145
* @param keys - List of keys
146
* @param values - List of values
147
* @returns Created map
148
*/
149
static zipmap(keys: string[], values: any[]): {[key: string]: any};
150
151
/**
152
* Merge multiple maps
153
* @param maps - Maps to merge
154
* @returns Merged map
155
*/
156
static merge(...maps: any[]): {[key: string]: any};
157
158
/**
159
* Check if a value exists in a list
160
* @param list - List to search
161
* @param value - Value to find
162
* @returns True if found
163
*/
164
static contains(list: any[], value: any): boolean;
165
166
/**
167
* Find the index of a value in a list
168
* @param list - List to search
169
* @param value - Value to find
170
* @returns Index number or -1
171
*/
172
static index(list: any[], value: any): number;
173
174
/**
175
* Get unique values from a list
176
* @param list - Input list
177
* @returns List with unique values
178
*/
179
static distinct(list: any[]): any[];
180
181
/**
182
* Sort a list of strings
183
* @param list - List to sort
184
* @returns Sorted list
185
*/
186
static sort(list: string[]): string[];
187
188
/**
189
* Reverse a list
190
* @param list - List to reverse
191
* @returns Reversed list
192
*/
193
static reverse(list: any[]): any[];
194
195
/**
196
* Get a slice of a list
197
* @param list - Source list
198
* @param start - Starting index
199
* @param end - Ending index
200
* @returns Sliced list
201
*/
202
static slice(list: any[], start: number, end: number): any[];
203
204
// Numeric Functions
205
/**
206
* Get the minimum value from a list
207
* @param list - List of numbers
208
* @returns Minimum value
209
*/
210
static min(list: number[]): number;
211
212
/**
213
* Get the maximum value from a list
214
* @param list - List of numbers
215
* @returns Maximum value
216
*/
217
static max(list: number[]): number;
218
219
/**
220
* Sum all values in a list
221
* @param list - List of numbers
222
* @returns Sum of all values
223
*/
224
static sum(list: number[]): number;
225
226
/**
227
* Get absolute value of a number
228
* @param num - Input number
229
* @returns Absolute value
230
*/
231
static abs(num: number): number;
232
233
/**
234
* Ceiling function
235
* @param num - Input number
236
* @returns Smallest integer greater than or equal to num
237
*/
238
static ceil(num: number): number;
239
240
/**
241
* Floor function
242
* @param num - Input number
243
* @returns Largest integer less than or equal to num
244
*/
245
static floor(num: number): number;
246
247
/**
248
* Round to nearest integer
249
* @param num - Input number
250
* @returns Rounded number
251
*/
252
static round(num: number): number;
253
254
// Type Functions
255
/**
256
* Get the type of a value
257
* @param value - Value to check
258
* @returns Type string
259
*/
260
static type(value: any): string;
261
262
/**
263
* Check if a value can be converted to a number
264
* @param value - Value to check
265
* @returns True if numeric
266
*/
267
static canNumber(value: any): boolean;
268
269
/**
270
* Check if a value can be converted to a string
271
* @param value - Value to check
272
* @returns True if convertible to string
273
*/
274
static canString(value: any): boolean;
275
276
// Date/Time Functions
277
/**
278
* Get current timestamp
279
* @returns Current timestamp string
280
*/
281
static timestamp(): string;
282
283
/**
284
* Format a timestamp
285
* @param format - Format string
286
* @param timestamp - Timestamp to format
287
* @returns Formatted timestamp
288
*/
289
static formatdate(format: string, timestamp: string): string;
290
291
/**
292
* Add duration to a timestamp
293
* @param timestamp - Base timestamp
294
* @param duration - Duration to add
295
* @returns New timestamp
296
*/
297
static timeadd(timestamp: string, duration: string): string;
298
299
// Encoding Functions
300
/**
301
* Base64 encode a string
302
* @param str - String to encode
303
* @returns Base64 encoded string
304
*/
305
static base64encode(str: string): string;
306
307
/**
308
* Base64 decode a string
309
* @param str - String to decode
310
* @returns Decoded string
311
*/
312
static base64decode(str: string): string;
313
314
/**
315
* URL encode a string
316
* @param str - String to encode
317
* @returns URL encoded string
318
*/
319
static urlencode(str: string): string;
320
321
/**
322
* JSON encode a value
323
* @param value - Value to encode
324
* @returns JSON string
325
*/
326
static jsonencode(value: any): string;
327
328
/**
329
* JSON decode a string
330
* @param str - JSON string to decode
331
* @returns Decoded value
332
*/
333
static jsondecode(str: string): any;
334
335
// Filesystem Functions
336
/**
337
* Read contents of a file
338
* @param path - File path
339
* @returns File contents as string
340
*/
341
static file(path: string): string;
342
343
/**
344
* Get directory portion of a file path
345
* @param path - File path
346
* @returns Directory path
347
*/
348
static dirname(path: string): string;
349
350
/**
351
* Get filename portion of a file path
352
* @param path - File path
353
* @returns Filename
354
*/
355
static basename(path: string): string;
356
357
/**
358
* Get file extension
359
* @param path - File path
360
* @returns File extension
361
*/
362
static fileextension(path: string): string;
363
364
/**
365
* Check if a file exists
366
* @param path - File path
367
* @returns True if file exists
368
*/
369
static fileexists(path: string): boolean;
370
371
// Crypto Functions
372
/**
373
* Generate MD5 hash
374
* @param str - String to hash
375
* @returns MD5 hash
376
*/
377
static md5(str: string): string;
378
379
/**
380
* Generate SHA1 hash
381
* @param str - String to hash
382
* @returns SHA1 hash
383
*/
384
static sha1(str: string): string;
385
386
/**
387
* Generate SHA256 hash
388
* @param str - String to hash
389
* @returns SHA256 hash
390
*/
391
static sha256(str: string): string;
392
393
/**
394
* Generate SHA512 hash
395
* @param str - String to hash
396
* @returns SHA512 hash
397
*/
398
static sha512(str: string): string;
399
400
/**
401
* Generate random UUID
402
* @returns UUID string
403
*/
404
static uuidv4(): string;
405
406
/**
407
* Generate random UUID v5
408
* @param namespace - Namespace UUID
409
* @param name - Name string
410
* @returns UUID v5 string
411
*/
412
static uuidv5(namespace: string, name: string): string;
413
}
414
```
415
416
**Usage Examples:**
417
418
```typescript
419
import { Fn, TerraformVariable, TerraformOutput } from "cdktf";
420
421
class MyStack extends TerraformStack {
422
constructor(scope: Construct, id: string) {
423
super(scope, id);
424
425
const environment = new TerraformVariable(this, "environment", {
426
type: "string",
427
default: "development"
428
});
429
430
const instanceCount = new TerraformVariable(this, "instance_count", {
431
type: "number",
432
default: 1
433
});
434
435
// String manipulation
436
const uppercaseEnv = Fn.upper(environment.stringValue);
437
const resourceName = Fn.join("-", ["app", uppercaseEnv, "server"]);
438
439
// Conditional logic
440
const instanceType = Fn.conditional(
441
Fn.contains(["production", "staging"], environment.stringValue),
442
"t3.large",
443
"t3.micro"
444
);
445
446
// Number operations
447
const maxInstances = Fn.max([instanceCount.numberValue, 1]);
448
const portRange = Fn.range(8000, 8000 + maxInstances.numberValue);
449
450
// Collection operations
451
const availabilityZones = ["us-east-1a", "us-east-1b", "us-east-1c"];
452
const selectedZones = Fn.slice(availabilityZones, 0, maxInstances);
453
454
// Date/time functions
455
const deploymentTime = Fn.timestamp();
456
const formattedTime = Fn.formatdate("YYYY-MM-DD", deploymentTime);
457
458
// Encoding functions
459
const userDataScript = `
460
#!/bin/bash
461
echo "Environment: ${environment.stringValue}" > /tmp/config
462
`;
463
const encodedUserData = Fn.base64encode(userDataScript);
464
465
// Crypto functions
466
const configHash = Fn.sha256(Fn.jsonencode({
467
environment: environment.stringValue,
468
instance_count: instanceCount.numberValue
469
}));
470
471
// File operations (for local files)
472
const sslCert = Fn.file("${path.module}/certificates/ssl.crt");
473
474
// Type checking
475
const isNumeric = Fn.canNumber(environment.stringValue);
476
477
// Create resources using function results
478
new AwsInstance(this, "app_server", {
479
ami: "ami-12345678",
480
instanceType: instanceType,
481
count: maxInstances,
482
userData: encodedUserData,
483
tags: {
484
Name: resourceName,
485
Environment: uppercaseEnv,
486
DeployedAt: formattedTime,
487
ConfigHash: configHash
488
}
489
});
490
491
// Output function results
492
new TerraformOutput(this, "resource_name", {
493
value: resourceName,
494
description: "Generated resource name"
495
});
496
497
new TerraformOutput(this, "selected_zones", {
498
value: selectedZones,
499
description: "Availability zones selected for deployment"
500
});
501
502
new TerraformOutput(this, "port_range", {
503
value: portRange,
504
description: "Port range for load balancer"
505
});
506
}
507
}
508
```
509
510
## Advanced Function Usage
511
512
### Complex Data Transformations
513
514
```typescript
515
import { Fn } from "cdktf";
516
517
// Transform a list of objects
518
const userList = new TerraformVariable(this, "users", {
519
type: "list(object({ name = string, role = string, active = bool }))"
520
});
521
522
// Extract active user names
523
const activeUsers = Fn.distinct(
524
Fn.sort([
525
for (user of userList.value)
526
user.name if user.active
527
])
528
);
529
530
// Create email map from user names
531
const emailMap = Fn.zipmap(
532
[for (user of activeUsers) user],
533
[for (user of activeUsers) Fn.lower(Fn.join("", [user, "@company.com"]))]
534
);
535
536
// Merge default tags with custom tags
537
const baseTags = {
538
ManagedBy: "terraform",
539
Project: "my-app"
540
};
541
542
const customTags = new TerraformVariable(this, "custom_tags", {
543
type: "map(string)",
544
default: {}
545
});
546
547
const finalTags = Fn.merge(baseTags, customTags.value);
548
```
549
550
### Validation and Error Handling
551
552
```typescript
553
import { Fn, TerraformVariable } from "cdktf";
554
555
const cidrBlock = new TerraformVariable(this, "vpc_cidr", {
556
type: "string",
557
validation: [{
558
condition: Fn.canRegexMatch("^10\\.", cidrBlock.stringValue),
559
errorMessage: "VPC CIDR must start with '10.'"
560
}]
561
});
562
563
const environment = new TerraformVariable(this, "environment", {
564
type: "string",
565
validation: [{
566
condition: Fn.contains(["dev", "staging", "prod"], environment.stringValue),
567
errorMessage: "Environment must be one of: dev, staging, prod"
568
}]
569
});
570
```