Terraform interpolation explained with example programs

What is interpolation?

Interpolation is the estimation of a value or set of values based on their context. In other words, Interpolation is a useful mathematical and statistical tool used to estimate values between two points.

What is Terraform interpolation?

In Terraform, string interpolation (or variable interpolation, variable substitution, or variable expansion) 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.

  • Embedded within strings in Terraform, whether you’re using the Terraform syntax or JSON syntax, you can interpolate other values. These interpolations are wrapped in ${}, such as ${var.foo}.
  • The interpolation syntax is powerful and allows you to reference variables, attributes of resources, call functions, etc.
  • You can perform simple math in interpolations, allowing you to write expressions such as ${count.index
  • 1}. And you can also use conditionals to determine a value based on some logic.
  • You can escape interpolation with double dollar signs: $${foo} will be rendered as a literal ${foo}.
  • The string interpolation syntax ${ … } has been part of Terraform since its initial release in 2015.
  • In Terraform 0.12, is now extended to include support for conditionals and for expressions. These new features are most useful within multi-line strings. Terraform is extending interpolation syntax used for strings (${}) to loops and conditionals (which implies interpolation syntax is still valid for strings).
# Configuration for Terraform 0.12

locals {
  lb_config = <<EOT
%{ for instance in opc_compute_instance.example ~}
server ${instance.label} ${instance.ip_address}:8080
%{ endfor }
EOT
}

More Reference

  • https://www.terraform.io/docs/configuration-0-11/interpolation.html
  • https://www.terraform.io/docs/configuration/expressions.html
Rajesh Kumar
Follow me