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.
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.
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.
Operators
Use the Op
object to include operators like !
, +
, and -
.
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.