Various tasks working with strings in HashiCorp Terraform is the most common type of code written when writing Infrastructure as Code (IaC) templates. String interpolation specifically is something that is almost impossible to write Terraform code without. The built-in Terraform functions for working with strings and string interpolation features are an extremely valuable and useful feature set of the Terraform language. These powerful features make evaluating strings, replacing placeholders, and building string values in Terraform done easily and flexible to fit whatever business requirements are necessary in the infrastructure code.

This article will explore the basics of string interpolation in Terraform, the multiple build-in string functions available, as well as multiple methods and techniques for working with strings in Terraform code.

Definition: String interpolation is the process of evaluating a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values

Wikipedia

Basics of String Interpolation in Terraform

HashiCorp Terraform uses a simple syntax for string interpolation within quoted ("") strings and heredoc strings, where the values enclosed in ${} characters are evaluated at runtime as an expression and replaced with their corresponding generated values. This simple yet powerful feature enables the full power of working with strings in Terraform using interpolation and all the built-in string functions.

Quoted Strings

A quoted string in Terraform is a sequence of characters enclosed in quotation marks (""). Quoted strings can be used to define string literals that are used in various parts of the Terraform project, such as locals, variables, resources, modules, and other configuration code.

The following is a simple example that defines a local variable in Terraform with a quoted string value:

locals {
  azure_region = "South Central US"
}

Since quoted strings use a double quote (") character, if the string value needs to use that character then an escape character must be used. The backslash (\) character is the escape character. Simply use the backslash immediately before a double quote and that double quote will be included in the string value.

The following is an example of using the escape character to enable double quote characters to be used within the value of a quoted string:

locals {
  hello_world = "Hello, \"Chris\"!"
}

In this example, the double quoted string includes the escape character to include double quotes within the string. As a result the final value of the hello_world local variable would be Hello, "Chris"!.

String interpolation within quoted strings uses the ${} characters to enclose the input or variable to place within the string. The input or variable reference will go between these characters as a placeholder where the value will be inserted at runtime.

The following example shows of using string interpolation to combine local variable values:

locals {
  name = "Chris"
  hello_world = "Hello, ${local.name}!"
}

This example shows using a single string interpolation within a quoted string. It is possible to use multiple ${} expressions within a single quoted string. The following example shows using multiple expressions within a single quoted string for performing string interpolation:

locals {
  name = "Chris"
  year = 2063
  hello_world = "${local.name} - ${local.year}"
}

In this example, you can see the use of 2 expressions used to place multiple local variable values into the final string value using interpolation. The local.year input value is also a Number, and when performing string interpolation the Number is converted to a String when the value is placed in the final string that is generated.

Quoted strings are an important and widely used feature in HashiCorp Terraform for defining string literals and working with configuration values.

Heredoc Strings

Heredoc strings are a way of defining multi-line string values in Terraform. Heredoc allows the defined string value to have the original formatting preserved in the final text value. Heredoc strings are extremely helpful when defining multi-line strings, such as code snippets, json, or configuration files while preserving the original formatting of the text.

Heredoc strings are enclosed in a pair of delimiters that start and end the string value. The start delimiter begins with << characters followed by a text value. Commonly the <<EOF value is used, but any text you choose can be used in place of EOF. Then the end delimiter is the value of that text, in this case it’s EOF.

The following is an example of a heredoc string in Terraform:

locals {
  json_value = <<EOF
{
  "database": {
    "connectionString": "connection value"
  },
  "title": "Some JSON"
}
EOF
}

In this example, the string value that represents the JSON content embedded within the heredoc string will be assigned as the value of the json_value local variable.

Alternatively, a different start and end delimiter could be chosen, such as <<JSON as well. Such as the following:

locals {
  json_value = <<JSON
{
  "database": {
    "connectionString": "connection value"
  },
  "title": "Some JSON"
}
JSON
}

Heredoc strings can also include string interpolation, allowing variable values and expressions to be placed within the string to be replaced at runtime when the value is generated. The following is an example of using string interpolation within a heredoc string:

locals {
  title = "Some JSON"
  json_value = <<EOF
{
  "database": {
    "connectionString": "connection value"
  },
  "title": "${local.title}"
}
EOF
}

Heredoc strings are a powerful and flexible featured in Terraform that enable the definition of multi-line strings while preserving their original formatting.

Most Common Terraform Built-in String Functions

HashiCorp Terraform include several built-in functions for working with strings. The following are the most commonly used string functions.

lower() Function

The lower() function accepts a string as an input and returns the given string in all lowercase.

"${lower(local.name)}"

replace() Function

The replace() function accepts a couple parameters that include a source string value, the substring value to find in the string, and the value to replace the substring within the source string value. The end resulting string with replacement is returned.

replace(string, substring, replacement)

The following is an example usage of the replace() function:

"${replace(local.text_value, "one", "1")}"

In this example, if the local.text_value is set to "this one value", then this will return the value of "this 1 value".

split() Function

The split() function accepts a couple parameters that include the separator string, and the string to divide by the given separator.

The following us an example usage of the split() function:

"${split(",", local.text_value)}"

In this example, if the local.text_value is set to "one,two,three", then this will return the following list:

[
  "one",
  "two",
  "three"
]

substr() Function

The substr() function can be used to extract a substring from the given string by an offset and maximum length specified.

substr(string, offset, length)

The following is an example of using the substr() function:

locals {
  message = "hello world"
  substring = "${substr(local.message, 0, 5)}"
}

In this example, the substr() function is passed the value of local.message, the offset of 0, and the length of 5. The offset of 0 starts the substring at the zero character (aka the start) and the length of 5 ends after the fifth character. The returned value in this example is hello.

The offset and length can also be set as negative values. This will perform the substring at the end of the string instead of the beginning. Using the same previous example of local.message, the following example will return world:

"${substr(local.message, -5, -1)}"

Also note, if the length specified to the substr() function is greater than the length of the string, then the remaining characters of the string will be returned.

trim() Function

The trim() function removes the specified set of characters from the start and end of the specified string.

"${trim("==hello world===", "=")}"

In this example, the = characters at the start and the end of the string will be removed and the resulting string will be returned.

The following is another example usage that has different characters to remove from the beginning and ending of the string:

"${trim("!?hello world!", "!?")}"

The string returned from this example will also be "hello world“.

upper() Function

The upper() function accepts a string as an input and returns the given string in all uppercase.

"${upper(local.name)}"

Conclusion

With the help of this article, you should have a good understanding of the basics of performing string interpolation in HashiCorp Terraform, as well as how to use the most commonly used built-in string manipulation functions. This article covered several of the built-in string functions, however there are several more in the full set of built-in Terraform string functions.

Chris Pietschmann is a Microsoft MVP, HashiCorp Ambassador, and Microsoft Certified Trainer (MCT) with 20+ years of experience designing and building Cloud & Enterprise systems. He has worked with companies of all sizes from startups to large enterprises. He has a passion for technology and sharing what he learns with others to help enable them to learn faster and be more productive.
Microsoft MVP HashiCorp Ambassador

Discover more from Build5Nines

Subscribe now to keep reading and get access to the full archive.

Continue reading