CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-cdktf

Cloud Development Kit for Terraform - programmatic infrastructure as code using familiar programming languages

Overview
Eval results
Files

tokens-expressions.mddocs/

Token System and Expressions

Comprehensive token resolution system for handling unresolved values and creating Terraform expressions, enabling dynamic configuration and cross-resource references.

Capabilities

Token Class

Static utilities for token manipulation, conversion, and resolution of unresolved values.

/**
 * Token manipulation and resolution utilities
 */
class Token {
  /**
   * Check if a value contains unresolved tokens
   * @param obj - Value to check
   * @returns True if the value contains unresolved tokens
   */
  static isUnresolved(obj: any): boolean;

  /**
   * Convert a value to a string, resolving tokens as needed
   * @param value - Value to convert
   * @param options - Encoding options
   * @returns String representation
   */
  static asString(value: any, options?: EncodingOptions): string;

  /**
   * Convert a value to a number, resolving tokens as needed
   * @param value - Value to convert
   * @returns Numeric representation
   */
  static asNumber(value: any): number;

  /**
   * Convert a value to a string array, resolving tokens as needed
   * @param value - Value to convert
   * @param options - Encoding options
   * @returns Array of strings
   */
  static asList(value: any, options?: EncodingOptions): string[];

  /**
   * Convert a value to a number array, resolving tokens as needed
   * @param value - Value to convert
   * @returns Array of numbers
   */
  static asNumberList(value: any): number[];

  /**
   * Convert a value to a string map, resolving tokens as needed
   * @param value - Value to convert
   * @param options - Encoding options
   * @returns Map of strings
   */
  static asStringMap(value: any, options?: EncodingOptions): {[key: string]: string};

  /**
   * Convert a value to a number map, resolving tokens as needed
   * @param value - Value to convert
   * @param options - Encoding options
   * @returns Map of numbers
   */
  static asNumberMap(value: any, options?: EncodingOptions): {[key: string]: number};

  /**
   * Convert a value to a boolean map, resolving tokens as needed
   * @param value - Value to convert
   * @param options - Encoding options
   * @returns Map of booleans
   */
  static asBooleanMap(value: any, options?: EncodingOptions): {[key: string]: boolean};

  /**
   * Convert a value to any type of map, resolving tokens as needed
   * @param value - Value to convert
   * @param options - Encoding options
   * @returns Map of any values
   */
  static asAnyMap(value: any, options?: EncodingOptions): {[key: string]: any};

  /**
   * Convert a value to any type, resolving tokens as needed
   * @param value - Value to convert
   * @returns Resolved value as IResolvable
   */
  static asAny(value: any): IResolvable;

  /**
   * Create a null value token
   * @returns Null value as IResolvable
   */
  static nullValue(): IResolvable;
}

Usage Examples:

import { Token, TerraformOutput, TerraformVariable } from "cdktf";

// Check if a value is unresolved
const variable = new TerraformVariable(this, "region", {
  type: "string",
  default: "us-east-1"
});

console.log(Token.isUnresolved(variable.stringValue)); // true
console.log(Token.isUnresolved("literal-string"));    // false

// Convert tokens to various types
const output = new TerraformOutput(this, "region_output", {
  value: variable.stringValue
});

const regionString = Token.asString(variable.stringValue);
const portNumber = Token.asNumber(variable.numberValue);
const tagsList = Token.asList(variable.listValue);
const tagsMap = Token.asStringMap({
  Environment: variable.stringValue,
  Project: "my-app"
});

Lazy Class

Lazy evaluation utilities for deferring computation until synthesis time.

/**
 * Lazy evaluation utilities for deferred computation
 */
class Lazy {
  /**
   * Create a lazy string value
   * @param producer - Function that produces the string value
   * @param options - Lazy string options
   * @returns Lazy string value
   */
  static stringValue(producer: IStringProducer, options?: LazyStringValueOptions): string;

  /**
   * Create a lazy number value
   * @param producer - Function that produces the number value
   * @returns Lazy number value
   */
  static numberValue(producer: INumberProducer): number;

  /**
   * Create a lazy list value
   * @param producer - Function that produces the list value
   * @param options - Lazy list options
   * @returns Lazy list value
   */
  static listValue(producer: IListProducer, options?: LazyListValueOptions): string[];

  /**
   * Create a lazy value of any type
   * @param producer - Function that produces the value
   * @param options - Lazy value options
   * @returns Lazy value as IResolvable
   */
  static anyValue(producer: IAnyProducer, options?: LazyAnyValueOptions): IResolvable;
}

Usage Examples:

import { Lazy, TerraformStack } from "cdktf";

class MyStack extends TerraformStack {
  constructor(scope: Construct, id: string) {
    super(scope, id);

    // Lazy string that computes at synthesis time
    const dynamicName = Lazy.stringValue({
      produce: () => {
        const timestamp = Date.now();
        return `resource-${timestamp}`;
      }
    });

    // Lazy list that filters resources
    const activeInstanceIds = Lazy.listValue({
      produce: () => {
        return this.getActiveInstances().map(i => i.id);
      }
    });
  }

  private getActiveInstances(): any[] {
    // Implementation to get active instances
    return [];
  }
}

Expression Functions

Functions for creating Terraform expressions and references.

/**
 * Create a reference to a Terraform resource or data source
 * @param identifier - The identifier to reference
 * @param stack - Optional stack context
 * @returns Resolvable reference
 */
function ref(identifier: string, stack?: TerraformStack): IResolvable;

/**
 * Create a conditional expression (ternary operator)
 * @param condition - Condition expression
 * @param trueValue - Value if condition is true
 * @param falseValue - Value if condition is false
 * @returns Conditional expression result
 */
function conditional(condition: Expression, trueValue: Expression, falseValue: Expression): any;

/**
 * Create a property access expression
 * @param target - Target object expression
 * @param args - Property access arguments
 * @returns Property access expression
 */
function propertyAccess(target: Expression, args: Expression[]): IResolvable;

/**
 * Create a function call expression
 * @param name - Function name
 * @param args - Function arguments
 * @returns Function call expression
 */
function call(name: string, args: Expression[]): IResolvable;

/**
 * Create a for expression for list/map comprehension
 * @param input - Input collection expression
 * @param valueExpression - Expression for each value
 * @param keyExpression - Optional expression for each key
 * @returns For expression result
 */
function forExpression(
  input: Expression,
  valueExpression: Expression,
  keyExpression?: Expression
): IResolvable;

/**
 * Create a reference to a dependable resource
 * @param dependable - The dependable resource
 * @returns Dependable reference string
 */
function dependable(dependable: ITerraformDependable): string;

/**
 * Create a raw string literal that won't be processed as a token
 * @param str - Raw string value
 * @returns Raw string as IResolvable
 */
function rawString(str: string): IResolvable;

Usage Examples:

import { ref, conditional, propertyAccess, forExpression } from "cdktf";

// Create references
const instanceRef = ref("aws_instance.web.id");
const crossStackRef = ref("data.terraform_remote_state.vpc.outputs.vpc_id", otherStack);

// Conditional expressions
const environmentName = conditional(
  ref("var.is_production"),
  "production",
  "development"
);

// Property access
const instanceAz = propertyAccess(ref("aws_instance.web"), ["availability_zone"]);

// For expressions - transform a list
const upperCaseNames = forExpression(
  ref("var.user_names"),
  call("upper", [ref("each.value")])
);

// For expressions - create a map from list
const userEmailMap = forExpression(
  ref("var.users"),
  ref("each.value.email"),
  ref("each.value.name")
);

Operator Expressions

Support for Terraform operators in expressions.

/**
 * Operator expression for mathematical and logical operations
 */
class OperatorExpression {
  /**
   * Create an operator expression
   * @param left - Left operand
   * @param operator - Operator string
   * @param right - Right operand
   */
  constructor(left: Expression, operator: string, right: Expression);

  /**
   * Addition operator
   * @param left - Left operand
   * @param right - Right operand
   * @returns Addition expression
   */
  static add(left: Expression, right: Expression): OperatorExpression;

  /**
   * Subtraction operator
   * @param left - Left operand
   * @param right - Right operand
   * @returns Subtraction expression
   */
  static subtract(left: Expression, right: Expression): OperatorExpression;

  /**
   * Multiplication operator
   * @param left - Left operand
   * @param right - Right operand
   * @returns Multiplication expression
   */
  static multiply(left: Expression, right: Expression): OperatorExpression;

  /**
   * Division operator
   * @param left - Left operand
   * @param right - Right operand
   * @returns Division expression
   */
  static divide(left: Expression, right: Expression): OperatorExpression;

  /**
   * Equality operator
   * @param left - Left operand
   * @param right - Right operand
   * @returns Equality expression
   */
  static equals(left: Expression, right: Expression): OperatorExpression;

  /**
   * Inequality operator
   * @param left - Left operand
   * @param right - Right operand
   * @returns Inequality expression
   */
  static notEquals(left: Expression, right: Expression): OperatorExpression;

  /**
   * Logical AND operator
   * @param left - Left operand
   * @param right - Right operand
   * @returns AND expression
   */
  static and(left: Expression, right: Expression): OperatorExpression;

  /**
   * Logical OR operator
   * @param left - Left operand
   * @param right - Right operand
   * @returns OR expression
   */
  static or(left: Expression, right: Expression): OperatorExpression;
}

Type Definitions

/**
 * Base interface for resolvable values
 */
interface IResolvable {
  /**
   * Stack trace of where this resolvable was created
   */
  readonly creationStack: string[];

  /**
   * Resolve the value during synthesis
   * @param context - Resolution context
   * @returns Resolved value
   */
  resolve(context: IResolveContext): any;

  /**
   * String representation of the resolvable
   * @returns String representation
   */
  toString(): string;
}

/**
 * Context provided during token resolution
 */
interface IResolveContext {
  /**
   * The scope in which resolution is taking place
   */
  readonly scope: IConstruct;

  /**
   * True if we are preparing for JSON output
   */
  readonly preparing: boolean;
}

/**
 * Union type for all expression types
 */
type Expression = string | number | boolean | IResolvable | any[];

/**
 * Options for encoding tokens as strings
 */
interface EncodingOptions {
  /**
   * Character to use for quotes
   * @default '"'
   */
  readonly displayHint?: string;
}

/**
 * Producer interface for lazy string values
 */
interface IStringProducer {
  /**
   * Produce the string value
   */
  produce(context?: IResolveContext): string;
}

/**
 * Producer interface for lazy number values
 */
interface INumberProducer {
  /**
   * Produce the number value
   */
  produce(context?: IResolveContext): number;
}

/**
 * Producer interface for lazy list values
 */
interface IListProducer {
  /**
   * Produce the list value
   */
  produce(context?: IResolveContext): string[];
}

/**
 * Producer interface for lazy any values
 */
interface IAnyProducer {
  /**
   * Produce the value
   */
  produce(context?: IResolveContext): any;
}

/**
 * Options for lazy string values
 */
interface LazyStringValueOptions {
  /**
   * Display hint for the lazy value
   */
  readonly displayHint?: string;
}

/**
 * Options for lazy list values
 */
interface LazyListValueOptions {
  /**
   * Display hint for the lazy value
   */
  readonly displayHint?: string;

  /**
   * Omit empty arrays from output
   * @default false
   */
  readonly omitEmpty?: boolean;
}

/**
 * Options for lazy any values
 */
interface LazyAnyValueOptions {
  /**
   * Display hint for the lazy value
   */
  readonly displayHint?: string;

  /**
   * Omit empty values from output
   * @default false
   */
  readonly omitEmptyArray?: boolean;
}

/**
 * Constants for for expression variables
 */
declare const FOR_EXPRESSION_KEY: string;
declare const FOR_EXPRESSION_VALUE: string;

Install with Tessl CLI

npx tessl i tessl/npm-cdktf

docs

annotations-aspects.md

backend-configuration.md

core-infrastructure.md

index.md

iterators-dynamic.md

providers-modules.md

provisioners.md

resources-data-sources.md

terraform-functions.md

testing.md

tokens-expressions.md

variables-outputs.md

tile.json