Build-in Function

Terraform has a set of built-in functions that may be used to perform various operations on values within expressions. The functions allow you to transform, manipulate, and combine values to produce desired outputs. Unfortunately, Terraform does not support the creation of user-defined functions. You cannot, therefore, create your own custom functions to extend the language.

Build-in Function Syntax

When calling a built-in function in Terraform, the basic syntax looks like this:
<FUNCTION NAME>(<ARGUMENT 1>, <ARGUMENT 2>)
Here's a breakdown of the syntax:
For example, if you were creating an S3 bucket using Terraform, the name of the bucket could be generated based on the environment, such as "dev", "prod", etc., and a prefix.
variable "environment" {
    type = string
    default = "prod"
}
variable "prefix" {
    type = string
    default = "service-bucket"
}
resource "aws_instance" "server" {
    name = "dev-server"
    instance_type = data.aws_instance.prod.instance_type
}
Here, the concat function combines the prefix and environment variables with a hyphen in between into a new string assigned to the bucket attribute of the aws_s3_bucket resource. The environment variable is set to "prod" here, while the prefix variable is set to "service-bucket", so the bucket name would be "service-bucket-prod".

Types of Build-in Functions

Terraform has 10 kinds of built-in functions that assist you in managing and transforming data. These can be divided into the following:
Expression
References to Named Values
Was this page helpful?