Need to turn an environment name into a label or combine tags before configuring a resource? A Terraform function is a named operation that accepts arguments and returns a value. Functions primarily transform configuration data; resources and data sources handle interactions with other systems. section 4.3
Call a function as function_name(arg1, arg2, …). Some take no arguments, such as timestamp; file requires a path; concat accepts at least two arguments. An argument can itself be an expression, which is evaluated before the call. section 4.3.1
Listing 4.15 Using functions to transform data
locals { #1
is_dev = startswith(var.environment, "dev-") #2
env_name = split(var.environment, "-")[1] #3
env_label = upper(local.env_name) #4
}
In a locals block, startswith checks an environment prefix, split extracts part of the name, and upper turns that part into a label. section 4.3.1
Choose a helper for the operation at hand:
- Use Terraform’s standard-library functions to transform values supplied to configuration blocks; merging tags is one practical use. section 4.3 section 4.1.6
- In Go-based Terratest tests, import helper packages as needed; these are test helpers, not Terraform expression functions. section 9.3.4
- When testing a provider resource, a helper can generate HCL configurations with different attributes instead of repeating configuration strings. section 12.6.8
Providers can also expose custom Terraform functions. Their interface supplies a name, a definition, and a run operation; unlike resources or data sources, they need no client or state handling. Provider functions are available starting with Terraform and OpenTofu v1.8. Older Terraform versions can still use the provider, but ignore its functions and report an error if a configuration calls one. section 4.3.2 section 12.7



















