Skip to main content

Implicit Type Conversion in Terraform

Where possible, Terraform automatically converts values from one type to another in order to produce the expected type. If this isn't possible, Terraform will produce a type mismatch error and you must update the configuration with a more suitable expression.

Example 01

If, You have declared a variable with the type - bool
and provided its value - "true" i.e. string as mentioned below.

# Variable Declaration
variable "example" { type = bool }

# Variable Definition
example = "true"

In this case, Terraform will internally transform the value to "true" to true (i.e. a bool type).

Example 02

If, You have declared a variable with the type - list(string)
and provided its value - ["a", 15, true] i.e. Tuple as mentioned below.

# Variable Declaration
variable "example" { type = list(string) }

# Variable Definition
example = ["a", 15, true]

In this case, Terraform will internally transform the value to ["a", "15", "true"] by converting the elements to the required string element type because list(string) type demands all the elements to have the string type.

Example 03

If, You have declared a variable with the type - map(string)
and provided its value - {name = ["Kristy", "Claudia"], age = 12} i.e. object as mentioned below.

# Variable Declaration
variable "example" { type = map(string) }

# Variable Definition
example = { name = ["Kristy", "Claudia"] age = 12 }

In this case, automatic conversion will fail and Terraform will raise a type mismatch error, since a tuple cannot be converted to a string. Here, although map(string) type demands all the key pair values to have the string type, but implicit type conversion is not possible, hence the type mismatch error.

Note: If you wish to apply absolutely no constraint to the given value, the any keyword can be used in isolation. In the below example, Terraform will replace any with the exact type of the given value and thus perform no type conversion whatsoever.

# Variable Declaration
variable "no_type_constraint" { type = any }