String Function

The String Function in Terraform configuration is used to transform and manipulate strings. You probably will need to convert strings to uppercase and lowercase, remove whitespace from strings, or replace substrings with new values.

Types of String Functions

Terraform provides the following types of String functions:

1. chomp Function

The chomp function removes the newline characters (\n) from the end of a string. It is commonly used if you have read a string from some file because files usually have newlines at the end. Removing the extra stuff cleans your string and gets it ready for further processing in your program. The syntax is
chomp(string)
For example
terraform console
> chomp("withnewline\n")
"withnewline"

2. startswith Function

The Terraform startswith function is a text-processing function used to determine whether a given string starts with a specified prefix. This function returns true if the input string is the specified prefix. It returns false if the input string does not result in the return of the specified prefix. Syntax:
startswith(string, prefix)
For example
terraform console
> startswith("terraform.com","terraform")
true
> startswith("terraform.com","puppet")
false

3. endswith Function

The function endswith checks if given string finishes with a specific suffix. The function returns true in case the input string ends with exactly the given suffix. It returns false if the input string does not finish with the given suffix. The syntax is
endswith(string, suffix)
For example
terraform console
> endswith("terraform.com","com")
true
> endswith("terraform.com","net")
false

4. indent Function

The indent function is a sort of text formatter for multi-line strings. It takes a string with multiple lines and adds spaces before each line except the first one. The syntax is
indent(num_spaces, string)
For example
terraform console
> indent(4, "This is a multi-line string.\nIt has multiple lines.")
<<EOT
This is a multi-line string.
    It has multiple lines.
EOT

5. split Function

The split function is a string cutter. It takes a string and breaks it apart into pieces of strings based on a specific separator character. Here's the syntax:
split(separator, string)
For example
terraform console
> split("," ,"init,plan,apply")
tolist([
    "init"
    "plan"
    "apply"
])

6. join Function

The join function is like a string assembler. It takes a list of strings and combines them into one long string. Using a separator you choose to put between each string, the syntax is
join(separator, list)
For example
terraform console
> join(",", ["terraform","plan","-no-color"])
"terraform,plan,-no-color"
> join(",", split(" ", "terraform plan -no-color"))
"terraform,plan,-no-color"

7. lower Function

The lower function in Terraform is invoked by calling it for the purpose of converting all the uppercase letters in a given string to lowercase. The syntax is
lower(string)
For example
terraform console
> lower("TERRAFORM")
"terraform"
> lower("TerraForm")
"terraform"
> lower("terraform")
"terraform"

8. upper Function

The upper function in Terraform converts all the lowercase letters of a given string to upper case. Syntax :
upper(string)
For example
terraform console
> upper("terraform")
"TERRAFORM"
> upper("TerraForm")
"TERRAFORM"
> upper("TERRAFORM")
"TERRAFORM"

9. title Function

In Terraform the title function returns a string with the first letter of every word capitalized. The syntax is
title(string)
For example
terraform console
> title("example string for uppercase")
"Example String For Uppercase"

10. strcontains Function

The strcontains function in Terraform checks if a certain substring occurs within a given string. It returns true if the input string contains the specified substring. It returns false if the input string does not contain the specified substring. Syntax:
strcontains(string, substr)
For example
terraform console
> strcontains("terraform plan","plan")
true
> strcontains("terraform plan","apply")
false

11. strrev Function

The strrev function in Terraform reverses the order of characters in a given string. Syntax:
strrev(string)
For example
terraform console
> strrev("terraform")
"mrofarret"

12. substr Function

The substr function in Terraform is used to extract a substring from a given string with 'offset' and 'length'. Syntax:
substr(string, offset, length)
Here is a breakdown of the syntax:
For example
terraform console
> substr("hello world", 6, 100)
"world"
If the offset is negative, it is be taken as the position from the end of the string. If the length parameter is negative, substr will return the remainder of the string beginning from the specified offset. Example:
terraform console
> substr("terraform plan", -4, 14)
"plan"
> substr("terraform plan", 4, -1)
"aform plan"
> substr("terraform plan", -4, -1)
"plan"
If the length parameter is larger than the remaining string length, the function will return the substring starting from the offset to the end of the string. For example
terraform console
> substr("terraform plan", 0, 1200)
"terraform plan"

13. trim Function

The trim function removes all occurrences of a specified set of characters from the start and end of a given string, but it leaves the middle part of the string unchanged. Syntax:
trim(string, str_character_set)
For example
terraform console
> trim("!hello!","!")
"hello"
> trim("!hel!lo!","!")
"hel!lo"
> trim("!!!hell!!o!!!","!")
"hell!!o"

14. trimprefix Function

The trimprefix function removes the given prefix from the start of a given string, if it actually starts with that. If the string does not have the given prefix at its start, it will return the original string unchanged. The basic syntax is
trimprefix(string, str_character_set)
For example
terraform console
> trimprefix("!hello!","!")
"hello!"
> trimprefix("!hel!lo!","!")
"hel!lo!"
> trimprefix("!!hello!","!")
"!hello!"

15. trimsuffix Function

The trimsuffix function removes the given suffix from the end of the provided string, if the string actually ends with that suffix. If it does not end with the suffix, the original string is returned unaltered. The syntax is
trimsuffix(string, str_character_set)
For example
terraform console
> trimsuffix("!hello!","!")
"!hello"
> trimsuffix("!hel!lo!","!")
"!hel!lo"
> trimsuffix("!!hello!!","!")
"!!hello!!"

16. trimspace Function

The trimspace function removes all whitespace characters (Regular spaces, Tabs, Newline characters and other similar characters) from the beginning and end of a given string. The syntax is
trimspace(string)
For example
terraform console
> trimspace(" Regular space")
"Regular space"
> trimspace("  Tabs")
"Tabs"
> trimspace("newline\n")
"newline"

17. regex Function

The regex function in Terraform searches a string for matches to a specific pattern and returns the first occurrence of the matching parts of the string. Its syntax is
regex(pattern, string)
Here is a breakdown of the syntax:
NOTE: In Terraform, when writing this pattern as a string, you must use double backslashes \\ to represent a single backslash \ in the pattern as Terraform already uses backslashes as an escape character in strings. For example, regex("\\d+", "mystring123").
The return type of the regex function depends on the existence of capture groups in the pattern:
terraform console
> regex("abc", "myabcstring")
"abc"
> regex("abc", "myabcstringabc")
"abc"
terraform console
> regex("(abc)(def)", "myabcdefstring")
[
    "abc"
    "def"
]
> regex("([a-z]+) ([a-z]+)","hello world")
[
    "hello"
    "world"
]
terraform console
> regex("(?<first>abc)(?<second>def)", "myabcdefstring")
  {
      "first": "abc"
      "second": "def"
  }
NOTE: You can't mix named and unnamed captures in one pattern. You need to choose either of these options. If the pattern does not match at all with the string, then the regex function will raise an error.

18. regexall Function

The Terraform regexall searches a string to find all occurrences of a pattern and returns a list of all matches. Syntax is
regexall(pattern, string)
Depending on the pattern's capture groups, the return value for regexall varies:
terraform console
> regex("abc", "myabcstringabc")
tolist([
    "abc"
    "abc"
])
terraform console
> regex("(abc)(def)", "myabcdefstring")
tolist([
    [
      "abc"
      "def"
    ]
])
> regex("([a-z]+) ([a-z]+)","hello world")
tolist([
    [
      "hello"
      "world"
    ]
])
terraform console
> regex("(?<first>abc)(?<second>def)", "myabcdefstring")
  tolist([
      {
        "first": "abc"
        "second": "def"
      }
  ])
The regexall function will not produce an error if no matches are found in the string. Instead, it will simply return an empty list. This behavior makes regexall a safe way to check if a string matches a pattern. You can do this by checking the length of the resulting list of matches. For example
terraform console
> regexall("(abc)(def)", "emptystring")
tolist([])
> length(regexall("(abc)(def)", "abcmiddleabc"))
2

19. replace Function

Replace function searches for a specified substring within a given string and replaces each occurrence with a new replacement string. The syntax is
replace(string, substring, replacement)
For example
terraform console
> replace("terraform plan", "plan", "apply")
"terraform apply"
> replace("terraform plan plan", "plan", "apply")
"terraform apply apply"
If the substring is enclosed in forward slashes (/), it's considered a regular expression. This allows for the possibility of more complex pattern matching. For instance
terraform console
> replace("terraform plan", "/[a-z]+/", "apply")
"apply apply"

20. format Function

The format function returns a string containing a number of values formatted according to a specification string. It is similar to the printf function in C and other languages. It offers an easy way to format multiple values into a single string. The syntax is
format(specification, argument...)
Here's the syntax breakdown:
For example
terraform console
> format("%s %d", "hello", 42)
"hello 42"
When using % sequences within a string, the system will automatically consume the next available argument, based on the first. You can override this with the addition of [n] before the verb letter (the letter that describes the data type). n is a decimal integer containing the one-based index of the argument to utilize. For example
terraform console
> format("%[2]s, %[1]s", "plan", "terraform")
"terraform plan"
The following formatting verbs are supported by the specification:
Escape Sequence
Usage
%%
Represents a literal percent sign, consuming no value.
%v
Provides default formatting based on the value type. This verb accepts all types, including items of null, list, and map types.
%#v
Produces a JSON serialization of the value, similar to the jsonencode function. This verb accepts all types, including items of null, list, and map types.
%t
Converts the value to a boolean and produces true or false.
%b
Converts the value to an integer number and produces its binary representation.
%d
Converts the value to an integer number and produces its decimal representation.
%o
Converts the value to an integer number and produces its octal representation.
%x
Converts the value to an integer number and produces its decimal representation.
%X
Similar to %x, but uses uppercase letters for the hexadecimal representation.
%e
Converts the value to a number and produces its scientific notation, like -1.234456e+78.
%E
Similar to %e, but uses an uppercase E to introduce the exponent.
%f
Converts the value to a number and produces its decimal fraction notation with no exponent, like 123.456.
%g
Produces a more compact representation, using %e for large exponents or %f otherwise.
%G
Similar to %g, but uses an uppercase E to introduce the exponent.
%s
Converts the value to a string and inserts the string's characters.
%q
Converts the value to a string and produces a JSON-quoted string representation.
In the case of decimal values, the width modifier provided by terraform enables you to specify the number of characters to be utilized in representing or expressing such value. It is specified by the addition of an optional decimal number right before the verb letter. You can also specify the precision after the (optional) width with a period (.) followed by a decimal number. If width or precision be not specified, Terraform will select a default value based on the given value.
Here are some examples:
Escape Sequence
Usage
%f
Uses the default width and precision.
%9f
Uses a width of 9 characters, with the default precision.
%.2f
Uses the default width, with a precision of 2 decimal places.
%9.2f
Uses a width of 9 characters, with a precision of 2 decimal places.
terraform console
> format("%f",7.3)
"7.300000"
> format("%10f",7.3)
"   7.300000"
> format("%.2f",7.3)
"7.30"
> format("%10.2f",7.3)
"   7.30"

21. formatlist Function

The formatlist function enables creation of lists of strings by formatting a set of values according to a specification string. It is very similar in use as the format function, except that it takes an iterable of values instead of a single value. The syntax is
formatlist(specification, argument...)
The spec argument is the formatting specification string. It uses the same syntax as the format function. The argument. argument can be a mix of list and non-list values. Example
terraform console
> formatlist("terraform %s", ["init", "plan", "apply"])
tolist([
    "terraform init"
    "terraform plan"
    "terraform apply"
])
> formatlist("%s %s", "terraform", ["init", "plan", "apply"])
tolist([
    "terraform init"
    "terraform plan"
    "terraform apply"
])

Related Pages

Feedback

Was this page helpful?