Cloud Development Kit for Terraform - programmatic infrastructure as code using familiar programming languages
Comprehensive access to Terraform's built-in functions for expressions, computations, and data transformations within CDKTF applications.
Static utilities providing access to all Terraform built-in functions for use in expressions and configurations.
/**
* Terraform built-in function utilities
*/
class Fn {
/**
* Generate a bcrypt hash of the given string with optional cost
* @param str - String to hash
* @param cost - Optional cost parameter (4-31)
* @returns Bcrypt hash string
*/
static bcrypt(str: string, cost?: number): string;
/**
* Conditional expression (ternary operator)
* @param condition - Condition to evaluate
* @param trueValue - Value if condition is true
* @param falseValue - Value if condition is false
* @returns Conditional result
*/
static conditional(condition: any, trueValue: any, falseValue: any): any;
/**
* Look up a value in a map with optional default
* @param inputMap - Map to search in
* @param key - Key to look up
* @param defaultValue - Default value if key not found
* @returns Looked up value
*/
static lookup(inputMap: any, key: string, defaultValue?: any): any;
/**
* Nested lookup in a map using a path array
* @param inputMap - Map to search in
* @param path - Array of keys for nested lookup
* @returns Nested value
*/
static lookupNested(inputMap: any, path: any[]): any;
/**
* Join a list of strings with a separator
* @param separator - String to use as separator
* @param list - List of strings to join
* @returns Joined string
*/
static join(separator: string, list: string[]): string;
/**
* Create a range of numbers
* @param start - Starting number
* @param limit - Ending number (exclusive)
* @param step - Step increment
* @returns Array of numbers
*/
static range(start: number, limit: number, step?: number): number[];
/**
* Create a raw string that won't be processed as an expression
* @param str - Raw string value
* @returns Raw string
*/
static rawString(str: string): string;
// String Functions
/**
* Convert string to lowercase
* @param str - Input string
* @returns Lowercase string
*/
static lower(str: string): string;
/**
* Convert string to uppercase
* @param str - Input string
* @returns Uppercase string
*/
static upper(str: string): string;
/**
* Get the length of a string, list, or map
* @param value - Value to measure
* @returns Length as number
*/
static length(value: any): number;
/**
* Extract substring from a string
* @param str - Source string
* @param offset - Starting position
* @param length - Number of characters
* @returns Substring
*/
static substr(str: string, offset: number, length: number): string;
/**
* Replace occurrences of a substring
* @param str - Source string
* @param substring - Substring to replace
* @param replacement - Replacement string
* @returns Modified string
*/
static replace(str: string, substring: string, replacement: string): string;
/**
* Trim whitespace from string
* @param str - Input string
* @returns Trimmed string
*/
static trim(str: string): string;
/**
* Split string into list by separator
* @param separator - Character to split on
* @param str - String to split
* @returns List of string parts
*/
static split(separator: string, str: string): string[];
// Collection Functions
/**
* Get keys from a map
* @param inputMap - Input map
* @returns List of keys
*/
static keys(inputMap: any): string[];
/**
* Get values from a map
* @param inputMap - Input map
* @returns List of values
*/
static values(inputMap: any): any[];
/**
* Create a map from lists of keys and values
* @param keys - List of keys
* @param values - List of values
* @returns Created map
*/
static zipmap(keys: string[], values: any[]): {[key: string]: any};
/**
* Merge multiple maps
* @param maps - Maps to merge
* @returns Merged map
*/
static merge(...maps: any[]): {[key: string]: any};
/**
* Check if a value exists in a list
* @param list - List to search
* @param value - Value to find
* @returns True if found
*/
static contains(list: any[], value: any): boolean;
/**
* Find the index of a value in a list
* @param list - List to search
* @param value - Value to find
* @returns Index number or -1
*/
static index(list: any[], value: any): number;
/**
* Get unique values from a list
* @param list - Input list
* @returns List with unique values
*/
static distinct(list: any[]): any[];
/**
* Sort a list of strings
* @param list - List to sort
* @returns Sorted list
*/
static sort(list: string[]): string[];
/**
* Reverse a list
* @param list - List to reverse
* @returns Reversed list
*/
static reverse(list: any[]): any[];
/**
* Get a slice of a list
* @param list - Source list
* @param start - Starting index
* @param end - Ending index
* @returns Sliced list
*/
static slice(list: any[], start: number, end: number): any[];
// Numeric Functions
/**
* Get the minimum value from a list
* @param list - List of numbers
* @returns Minimum value
*/
static min(list: number[]): number;
/**
* Get the maximum value from a list
* @param list - List of numbers
* @returns Maximum value
*/
static max(list: number[]): number;
/**
* Sum all values in a list
* @param list - List of numbers
* @returns Sum of all values
*/
static sum(list: number[]): number;
/**
* Get absolute value of a number
* @param num - Input number
* @returns Absolute value
*/
static abs(num: number): number;
/**
* Ceiling function
* @param num - Input number
* @returns Smallest integer greater than or equal to num
*/
static ceil(num: number): number;
/**
* Floor function
* @param num - Input number
* @returns Largest integer less than or equal to num
*/
static floor(num: number): number;
/**
* Round to nearest integer
* @param num - Input number
* @returns Rounded number
*/
static round(num: number): number;
// Type Functions
/**
* Get the type of a value
* @param value - Value to check
* @returns Type string
*/
static type(value: any): string;
/**
* Check if a value can be converted to a number
* @param value - Value to check
* @returns True if numeric
*/
static canNumber(value: any): boolean;
/**
* Check if a value can be converted to a string
* @param value - Value to check
* @returns True if convertible to string
*/
static canString(value: any): boolean;
// Date/Time Functions
/**
* Get current timestamp
* @returns Current timestamp string
*/
static timestamp(): string;
/**
* Format a timestamp
* @param format - Format string
* @param timestamp - Timestamp to format
* @returns Formatted timestamp
*/
static formatdate(format: string, timestamp: string): string;
/**
* Add duration to a timestamp
* @param timestamp - Base timestamp
* @param duration - Duration to add
* @returns New timestamp
*/
static timeadd(timestamp: string, duration: string): string;
// Encoding Functions
/**
* Base64 encode a string
* @param str - String to encode
* @returns Base64 encoded string
*/
static base64encode(str: string): string;
/**
* Base64 decode a string
* @param str - String to decode
* @returns Decoded string
*/
static base64decode(str: string): string;
/**
* URL encode a string
* @param str - String to encode
* @returns URL encoded string
*/
static urlencode(str: string): string;
/**
* JSON encode a value
* @param value - Value to encode
* @returns JSON string
*/
static jsonencode(value: any): string;
/**
* JSON decode a string
* @param str - JSON string to decode
* @returns Decoded value
*/
static jsondecode(str: string): any;
// Filesystem Functions
/**
* Read contents of a file
* @param path - File path
* @returns File contents as string
*/
static file(path: string): string;
/**
* Get directory portion of a file path
* @param path - File path
* @returns Directory path
*/
static dirname(path: string): string;
/**
* Get filename portion of a file path
* @param path - File path
* @returns Filename
*/
static basename(path: string): string;
/**
* Get file extension
* @param path - File path
* @returns File extension
*/
static fileextension(path: string): string;
/**
* Check if a file exists
* @param path - File path
* @returns True if file exists
*/
static fileexists(path: string): boolean;
// Crypto Functions
/**
* Generate MD5 hash
* @param str - String to hash
* @returns MD5 hash
*/
static md5(str: string): string;
/**
* Generate SHA1 hash
* @param str - String to hash
* @returns SHA1 hash
*/
static sha1(str: string): string;
/**
* Generate SHA256 hash
* @param str - String to hash
* @returns SHA256 hash
*/
static sha256(str: string): string;
/**
* Generate SHA512 hash
* @param str - String to hash
* @returns SHA512 hash
*/
static sha512(str: string): string;
/**
* Generate random UUID
* @returns UUID string
*/
static uuidv4(): string;
/**
* Generate random UUID v5
* @param namespace - Namespace UUID
* @param name - Name string
* @returns UUID v5 string
*/
static uuidv5(namespace: string, name: string): string;
}Usage Examples:
import { Fn, TerraformVariable, TerraformOutput } from "cdktf";
class MyStack extends TerraformStack {
constructor(scope: Construct, id: string) {
super(scope, id);
const environment = new TerraformVariable(this, "environment", {
type: "string",
default: "development"
});
const instanceCount = new TerraformVariable(this, "instance_count", {
type: "number",
default: 1
});
// String manipulation
const uppercaseEnv = Fn.upper(environment.stringValue);
const resourceName = Fn.join("-", ["app", uppercaseEnv, "server"]);
// Conditional logic
const instanceType = Fn.conditional(
Fn.contains(["production", "staging"], environment.stringValue),
"t3.large",
"t3.micro"
);
// Number operations
const maxInstances = Fn.max([instanceCount.numberValue, 1]);
const portRange = Fn.range(8000, 8000 + maxInstances.numberValue);
// Collection operations
const availabilityZones = ["us-east-1a", "us-east-1b", "us-east-1c"];
const selectedZones = Fn.slice(availabilityZones, 0, maxInstances);
// Date/time functions
const deploymentTime = Fn.timestamp();
const formattedTime = Fn.formatdate("YYYY-MM-DD", deploymentTime);
// Encoding functions
const userDataScript = `
#!/bin/bash
echo "Environment: ${environment.stringValue}" > /tmp/config
`;
const encodedUserData = Fn.base64encode(userDataScript);
// Crypto functions
const configHash = Fn.sha256(Fn.jsonencode({
environment: environment.stringValue,
instance_count: instanceCount.numberValue
}));
// File operations (for local files)
const sslCert = Fn.file("${path.module}/certificates/ssl.crt");
// Type checking
const isNumeric = Fn.canNumber(environment.stringValue);
// Create resources using function results
new AwsInstance(this, "app_server", {
ami: "ami-12345678",
instanceType: instanceType,
count: maxInstances,
userData: encodedUserData,
tags: {
Name: resourceName,
Environment: uppercaseEnv,
DeployedAt: formattedTime,
ConfigHash: configHash
}
});
// Output function results
new TerraformOutput(this, "resource_name", {
value: resourceName,
description: "Generated resource name"
});
new TerraformOutput(this, "selected_zones", {
value: selectedZones,
description: "Availability zones selected for deployment"
});
new TerraformOutput(this, "port_range", {
value: portRange,
description: "Port range for load balancer"
});
}
}import { Fn } from "cdktf";
// Transform a list of objects
const userList = new TerraformVariable(this, "users", {
type: "list(object({ name = string, role = string, active = bool }))"
});
// Extract active user names
const activeUsers = Fn.distinct(
Fn.sort([
for (user of userList.value)
user.name if user.active
])
);
// Create email map from user names
const emailMap = Fn.zipmap(
[for (user of activeUsers) user],
[for (user of activeUsers) Fn.lower(Fn.join("", [user, "@company.com"]))]
);
// Merge default tags with custom tags
const baseTags = {
ManagedBy: "terraform",
Project: "my-app"
};
const customTags = new TerraformVariable(this, "custom_tags", {
type: "map(string)",
default: {}
});
const finalTags = Fn.merge(baseTags, customTags.value);import { Fn, TerraformVariable } from "cdktf";
const cidrBlock = new TerraformVariable(this, "vpc_cidr", {
type: "string",
validation: [{
condition: Fn.canRegexMatch("^10\\.", cidrBlock.stringValue),
errorMessage: "VPC CIDR must start with '10.'"
}]
});
const environment = new TerraformVariable(this, "environment", {
type: "string",
validation: [{
condition: Fn.contains(["dev", "staging", "prod"], environment.stringValue),
errorMessage: "Environment must be one of: dev, staging, prod"
}]
});