0
0
TerraformHow-ToBeginner · 3 min read

How to Use the Split Function in Terraform: Syntax and Examples

In Terraform, use the split(delimiter, string) function to divide a string into a list of substrings based on the specified delimiter. It returns a list of strings split wherever the delimiter appears in the original string.
📐

Syntax

The split function takes two arguments: the delimiter which is the character or string to split on, and the string which is the text you want to split. It returns a list of substrings.

  • delimiter: The separator used to split the string.
  • string: The input string to split.
terraform
split(delimiter, string)
💻

Example

This example shows how to split a comma-separated string into a list of strings using split. It demonstrates how the function breaks the string at each comma.

terraform
variable "csv_string" {
  default = "apple,banana,cherry"
}

output "fruits_list" {
  value = split(",", var.csv_string)
}
Output
["apple", "banana", "cherry"]
⚠️

Common Pitfalls

Common mistakes include:

  • Using the wrong delimiter that does not exist in the string, which returns the whole string as a single list item.
  • Passing a non-string type as the second argument, which causes errors.
  • Expecting split to trim spaces automatically; it does not remove spaces around substrings.

Always ensure the delimiter matches exactly and trim spaces if needed separately.

terraform
/* Wrong: delimiter does not match */
output "wrong_split" {
  value = split(";", "apple,banana,cherry")
}

/* Right: correct delimiter used */
output "correct_split" {
  value = split(",", "apple,banana,cherry")
}
Output
wrong_split = ["apple,banana,cherry"] correct_split = ["apple", "banana", "cherry"]
📊

Quick Reference

FunctionDescriptionExample
split(delimiter, string)Splits a string into a list by delimitersplit(",", "a,b,c") → ["a", "b", "c"]
trim(string)Removes spaces from start and end of stringtrim(" apple ") → "apple"
join(delimiter, list)Joins list elements into a stringjoin(",", ["a", "b"]) → "a,b"

Key Takeaways

Use split(delimiter, string) to convert a string into a list by splitting at the delimiter.
The delimiter must exactly match the separator in the string for correct splitting.
split does not trim spaces; use trim() if you need to clean substrings.
Passing a wrong delimiter returns the whole string as a single list item.
Always provide string arguments to split to avoid errors.