Terraform
Functions
Terraform provides a set of built-in functions that transform and combine values within Terraform configurations. The Terraform function documentation contains a complete list. You can also use your editor autocompletion on the Fn
object to find available options.
Functions can handle normal and token values and will return either tokenized values or IResolvable
values.
When to Use Terraform Functions
Use Terraform functions when you need to calculate new values based on runtime values that are unknown before Terraform applies a configuration. For example, instance IDs that cloud providers assign on creation.
When inputs are available before synthesizing your code (e.g. local files), we recommend transforming the values with your preferred programming language.
Usage Example
The following example uses a Data Source from the AWS Provider to fetch the Availability Zones of the given region. As this data is unknown until Terraform applies the configuration, this CDKTF application uses both Terraform Outputs and the Terraform element
function.
The element
function gets the first element from the list of Availability Zone names.
import { TerraformStack, TerraformVariable } from "cdktf";
import { Construct } from "constructs";
import { AwsProvider } from "@cdktf/provider-aws/lib/aws-provider";
import { Fn, TerraformOutput } from "cdktf";
import { DataAwsAvailabilityZones } from "@cdktf/provider-aws/lib/data-aws-availability-zones";
export class FunctionsStack extends TerraformStack {
constructor(scope: Construct, id: string) {
super(scope, id);
new AwsProvider(this, "aws", {
region: "us-west-2",
});
const zones = new DataAwsAvailabilityZones(this, "zones", {
state: "available",
});
new TerraformOutput(this, "first-zone", {
value: Fn.element(zones.names, 0),
});
}
}
Special functions
Property Access Helpers
To access nested properties from untyped objects or other datasources that return a dynamic datatype, use the Terraform function lookup
or, for nested access, the function "Fn.lookupNested()" which is a function offered by CDKTF that allows to avoid nesting Fn.lookup
calls.
const v = new TerraformVariable(this, "complex_object", {
type: "object({users: list(object({name: string}))})",
});
new TerraformOutput(this, "users", { value: Fn.lookup(v.value, "users") });
new TerraformOutput(this, "first_user_name", {
value: Fn.lookupNested(v.value, ["users", 0, "name"]),
});
v = TerraformVariable(self, "complex-object",
type = 'object({users: list(object({name: string}))})',
)
TerraformOutput(self, 'users',
value=Fn.lookup(v.string_value, "users")
)
TerraformOutput(self, 'first_user_name',
value=Fn.lookup_nested(v.string_value, ["users", 0, "name"])
)
TerraformVariable v = new TerraformVariable(this, "complex_object", TerraformVariableConfig.builder()
.type("object({users: list(object({name: string}))})")
.build());
new TerraformOutput(this, "users", TerraformOutputConfig.builder()
.value(Fn.lookup(v.getValue(), "users"))
.build());
new TerraformOutput(this, "first-user-name", TerraformOutputConfig.builder()
.value(Fn.lookupNested(v.getValue(), Arrays.asList("users", "0", "name")))
.build());
TerraformVariable v = new TerraformVariable(this, "complex_object", new TerraformVariableConfig
{
Type = "object({users: list(object({name: string}))})",
});
new TerraformOutput(this, "users", new TerraformOutputConfig
{
Value = Fn.Lookup(v.Value, "users")
});
new TerraformOutput(this, "first-user-name", new TerraformOutputConfig
{
Value = Fn.LookupNested(v.Value, new[] { "users", "0", "name" })
});
v := cdktf.NewTerraformVariable(stack, jsii.String("complex-object"), &cdktf.TerraformVariableConfig{
Type: jsii.String("object({users: list(object({name: string}))})"),
})
cdktf.NewTerraformOutput(stack, jsii.String("users"), &cdktf.TerraformOutputConfig{
Value: cdktf.Fn_Lookup(v.Value(), jsii.String("users"), nil),
})
cdktf.NewTerraformOutput(stack, jsii.String("first-user-name"), &cdktf.TerraformOutputConfig{
Value: cdktf.Fn_LookupNested(v.Value(), &[]interface{}{"users", 0, "name"}),
})
Raw string helper
Another helper function offered by CDKTF is Fn.rawString
which can be used to escape raw strings that contain characters that CDKTF or Terraform would try to interpret otherwise.
new TerraformOutput(this, "quotes", {
value: Fn.rawString(`"b"`),
});
new TerraformOutput(this, "template", {
value: Fn.rawString("${TEMPLATE}"),
});
TerraformOutput(self, 'quotes',
value=Fn.raw_string('"b"')
)
TerraformOutput(self, 'template',
value=Fn.raw_string('${TEMPLATE}')
)
new TerraformOutput(this, "quotes", TerraformOutputConfig.builder()
.value(Fn.rawString("\"b\""))
.build());
new TerraformOutput(this, "template", TerraformOutputConfig.builder()
.value(Fn.rawString("${TEMPLATE}"))
.build());
new TerraformOutput(this, "quotes", new TerraformOutputConfig
{
Value = Fn.RawString("\"b\"")
});
new TerraformOutput(this, "template", new TerraformOutputConfig
{
Value = Fn.RawString("${TEMPLATE}")
});
cdktf.NewTerraformOutput(stack, jsii.String("quotes"), &cdktf.TerraformOutputConfig{
Value: cdktf.Fn_RawString(jsii.String("\"b\"")),
})
cdktf.NewTerraformOutput(stack, jsii.String("template"), &cdktf.TerraformOutputConfig{
Value: cdktf.Fn_RawString(jsii.String("${TEMPLATE}")),
})
Operators
Use the Op
object to include operators like !
, +
, and -
.
import { Fn, TerraformOutput } from "cdktf";
import { Op } from "cdktf";
const zones = new DataAwsAvailabilityZones(this, "zones", {
state: "available",
});
// ...
new TerraformOutput(this, "half-of-the-zone", {
value: Op.div(Fn.lengthOf(zones.names), 2),
});
Using Terraform built-in functions directly within strings
It is also possible to use all built-in Terraform functions without using CDKTF's Fn.*
functions described above. To write Terraform built-in functions the same as you would in HCL, simply wrap the desired string within the HCL ${
and }
syntax. Note: CDKTF doesn't do any further processing within the escaped syntax (${
and }
), and thus is unable to handle nested escape syntaxes yet.
import { Fn, TerraformOutput } from "cdktf";
import { Op } from "cdktf";
import { DataAwsAvailabilityZones } from "@cdktf/provider-aws/lib/data-aws-availability-zones";
const zones = new DataAwsAvailabilityZones(this, "zones", {
state: "available",
});
// ...
new TerraformOutput(this, "half-of-the-zone-raw", {
value: `\${length(${zones.fqn}.names) / 2}`,
});