Built-in Functions

Terraform ships dozens of functions for strings, numbers, collections, and encoding.

Syntaxmerge(map1, map2) join(", ", list) format("%s-%d", name, n)

Terraform includes many built-in functions for transforming values. You cannot define your own, but the built-ins cover most needs.

Handy categories

  • Stringupper, lower, replace, format, join, split.
  • Collectionlength, concat, merge, lookup, flatten.
  • Encodingjsonencode, base64encode.
  • Filesystemfile, templatefile.

Test any function interactively with terraform console.

Example

Example · hcl
locals {
  base_tags = { ManagedBy = "Terraform" }
  env_tags  = { Environment = var.environment }

  # merge combines maps; later keys win
  all_tags = merge(local.base_tags, local.env_tags)

  upper_name = upper(var.project)
  csv_zones  = join(",", var.availability_zones)
}

When to use it

  • An engineer uses toset(var.user_list) to convert a list variable to a set before passing it to for_each, eliminating duplicate entries automatically.
  • A team uses jsonencode() to build an IAM policy document as a native HCL map and encode it to the JSON string that aws_iam_policy expects.
  • A module uses cidrsubnet() to calculate subnet CIDR blocks algorithmically from a base VPC CIDR and an index, avoiding hard-coded subnet ranges.

More examples

String and collection functions

Shows several common string and collection functions: upper, trimspace, join, and toset (which de-duplicates a list).

Example · hcl
locals {
  upper_env  = upper(var.environment)          # "PROD"
  trimmed    = trimspace("  myapp  ")           # "myapp"
  joined     = join("-", ["myapp", var.env])   # "myapp-prod"
  unique_azs = toset(["us-east-1a", "us-east-1a", "us-east-1b"])  # set of 2
}

cidrsubnet for IP planning

Uses cidrsubnet() to derive multiple /24 subnets from a /16 VPC CIDR without hard-coding the subnet addresses.

Example · hcl
variable "vpc_cidr" { default = "10.0.0.0/16" }

locals {
  # Carve /24s out of the /16
  public_cidr  = cidrsubnet(var.vpc_cidr, 8, 0)  # 10.0.0.0/24
  private_cidr = cidrsubnet(var.vpc_cidr, 8, 1)  # 10.0.1.0/24
  data_cidr    = cidrsubnet(var.vpc_cidr, 8, 2)  # 10.0.2.0/24
}

jsonencode for IAM policy

Uses jsonencode() to write the IAM policy as readable HCL rather than an escaped JSON string, keeping it maintainable.

Example · hcl
resource "aws_iam_role_policy" "s3_read" {
  name = "s3-read"
  role = aws_iam_role.app.id

  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Effect   = "Allow"
      Action   = ["s3:GetObject", "s3:ListBucket"]
      Resource = ["arn:aws:s3:::${aws_s3_bucket.data.id}/*"]
    }]
  })
}

Discussion

  • Be the first to comment on this lesson.