Type Conversion Function
Types of Type Conversion Functions
Terraform provides the following types of Type Conversion functions:
1. can Function
The can function in Terraform is used to evaluate a given expression and return a boolean value indicating whether the expression produced a result without any errors. The syntax of can is
can(expression)
It can only catch and handle the errors that occur in runtime when data is being accessed or evaluated. Anything that could be detected by Terraform before its runtime cannot be caught by it. Examples include: Syntax invalid, Malformed resource references (Typing the wrong resource name, or using a resource that does not exist).
The primary purpose of the can function is to turn an error condition into a boolean validation result when writing custom variable validation rules. This is useful when you want to check the validity of a value without causing a hard failure in your Terraform configuration. For example
For example
terraform console
> can(timeadd("2018-05-13T07:44:12Z", "2"))
false
> can(timeadd("2018-05-13T07:44:12Z", "2s"))
true
variable "cidr_block" { type = string validation { condition = can(cidrsubnet(var.cidr_block, 0, 0)) error_message = "The cidr_block argument requires a valid IPv4 or IPv6 CIDR block." } }
Here, the can function checks if the variable cidr_block is a valid IPv4 or IPv6 CIDR block. In case the cidrsubnet fails (i.e., returns an error) based on the parsing of the cidr_block variable, the can function will catch that error and return false, which triggers the error message.
NOTE: The can function catches errors, but for most purposes, it is better to use the try function since it provides a more compact way of specifying fallback values for failing expressions.
2. sensitive Function
The sensitive function in Terraform is used to marks a value as sensitive. Once a value is marked as sensitive, Terraform will handle it with extra security precautions, such as not displaying its value in output. The syntax is
sensitive(value)
The sensitive function is primarily useful when a sensitive value is generated internal to a module, for example when reading sensitive data from a file on disk. Example
resource "null_resource" "sensitive_usage" {
provisioner "local-exec" {
command = "echo '${sensitive(file("./sensitive.txt"))}'"
}
}
Terraform will perform the following actions:
# module.executor.null_resource.module_executor will be created
+ resource "null_resource" "module_executor" {
+ id = (known after apply)
}
Plan: 1 to add, 0 to change, 0 to destroy.
Enter a value: yes
module.executor.null_resource.sensitive_usage: Creating...
module.executor.null_resource.sensitive_usage: Provisioning with 'local-exec'...
module.executor.null_resource.sensitive_usage: (output suppressed due to sensitive value in config)
module.executor.null_resource.sensitive_usage: (output suppressed due to sensitive value in config)
null_resource.root_executor: Creation complete after 0s [id=4425172414869377883]
3. nonsensitive Function
The nonsensitive function in Terraform removes the sensitive marking from a value and exposes the value in terraform output. The syntax is
nonsensitive(value)
This function should be used with caution, as it can cause values that Terraform would normally consider sensitive to be displayed clearly in the Terraform output.
For example
terraform console
> nonsensitive("non-sensitive-value")
"non-sensitive-value"
4. issensitive Function
The issensitive function is used in order to check if a given value is marked sensitive in Terraform. It returns true if the value is treated as sensitive and false otherwise. Syntax:
issensitive(expression)
The issensitive function can be useful in situations where you need to programmatically determine whether a value is sensitive or not, such as when writing conditional logic based on the sensitivity of a value, for example.
terraform console
> issensitive(sensitive("secret"))
true
> issensitive("insensitive-value")
false
5. tobool Function
The tobool function in Terraform is used to convert a value to a boolean data type. The syntax is
formatdate(spec, timestamp)
The tobool function is primarily for use in module outputs where one might want to make sure the returned values are of the correct type (in this case, boolean).
tobool function can only convert the following values into boolean:
- Existing boolean values.
- The string "true".
- The string "false".
- The value null.
For Example
terraform console
> tobool(true)
true
> tobool("false")
false
> tobool(null)
tobool(null)
Terraform generally performs automatic type conversions where necessary so you usually don't need to use the tobool function. However, it is useful when you need to explicitly convert a value to a boolean.
6. tolist Function
The tolist function in Terraform is used to convert a value to a list data type. Syntax for the usage of the tolist function is
tolist(value)
The tolist function is primarily intended for use in module outputs, where you may need to ensure that the returned values are of the correct type (in this case, a list).
tolist function can only convert the following values into a list:
- Existing list values.
- set values.
For Example
terraform console
> tolist([1, 2, 3, 4])
tolist([
1,
2,
3,
4,
])
> tolist("single-value")
Invalid value for "v" parameter: cannot convert string to list of any single type.
Terraform does support lists, but all elements in a list must have the same data type. If you have a list that contains mixed types, then Terraform will perform type conversion on it to ensure that all elements are of the most general data type. If these are all primitive types (for example, string, number, and boolean) then Terraform will type convert all of these to the most general type, usually string. For example
terraform console
> tolist([1, 2, 3, "4"])
tolist([
"1",
"2",
"3",
"4",
])
> tolist([1, 2, 3, true])
Invalid value for "v" parameter: cannot convert tuple to list of any single type.
In general, you don't have to use the tolist function, because Terraform generally performs automatic type conversions when required. But this is helpful where one wants to explicitly convert a value into a list.
7. tomap Function
The tomap function in Terraform is used to convert a value to a map data type. Syntax for the usage of the tomap function is
tomap(value)
For Example
terraform console
> tomap({"key1": 1, "key2": 2})
tomap([
"key1": 1,
"key2": 2,
])
> tomap([1, 2, 3, 4])
Invalid value for "v" parameter: cannot convert tuple to map of any single type.
> tomap(2)
Invalid value for "v" parameter: cannot convert number to map of any single type.
In Terraform, a map is one of the data types that require all their value elements to be of the same data type. Once you have a map of several types of values, Terraform will implicitly convert those types so that all values are of the most general data type. If there's a mix of the different primitive types (string, number, and boolean) Terraform again does implicit type conversion of all values into the most general data type, usually string. For example
terraform console
> tomap({"key1": "string", "key2": 2, "key3": true})
tomap([
"key1": "string",
"key2": "2",
"key2": "true",
])
Terraform will generally perform implicit type conversions where needed, so explicit type conversions are rarely necessary. However, You can use explicit type conversion functions, like tomap, to help normalize types of values returned in module outputs.
NOTE: tomap only supports map structure as an input.
8. tonumber Function
The tonumber function in Terraform is used to convert its argument to a number value. The syntax is
tonumber(value)
tonumber function can only convert the following values into a number:
- Existing number values.
- Strings containing decimal representations of numbers.
For Example
terraform console
> tonumber(2)
2
> tonumber("34")
34
> tonumber(null)
tonumber(null)
Like the tomap function, explicit type conversions with tonumber are rarely needed in Terraform, as it will perform type conversions where required. You can, however use the tonumber function to normalize the types of values returned in module outputs.
9. toset Function
The toset function in Terraform is used to convert its argument into a set value. Syntax:
toset(value)
The input argument to toset should be a list value. The toset function converts this list into a set that will have the following characteristic features:
- Discards the ordering of the elements in the list.
- Removes any duplicate elements from the list.
terraform console
> toset([1, 2, 3, 4])
toset([
1,
2,
3,
4,
])
> toset([1, 2, 3, 4, 2, 4])
toset([
1,
2,
3,
4,
])
Terraform sets of elements must all be of the same data type. If you happen to have a set that contains the elements of mixed types, then Terraform will perform type conversion to make sure all the elements are of the most general data type. If it contains different primitive types (string, number, and boolean) Terraform will convert all the elements into most general, often string. Here is an example:
terraform console
> toset([1, 2, 3, "4", 4, "1"])
toset([
"1",
"2",
"3",
"4",
])
> toset([1, 2, 3, true])
Invalid value for "v" parameter: cannot convert tuple to set of any single type.
Terraform generally does automatic type conversions when necessary, so you usually don't need to use the toset function. However, it can be handy for situations where you want to explicitly convert a value into a set.
The order of elements in the set is not maintained. When you access or loop a set, elements may not show up in the same order as they are added. For example
terraform console
> toset([3, "4", 4, "1", 2])
toset([
"1",
"2",
"3",
"4",
])
10. tostring Function
The tostring function in Terraform converts its argument to a string value. Syntax
tostring(value)
For example
terraform console
> tostring("string")
"string
> tostring(45)
"45
> tostring(true)
"true
> tostring(null)
tostring([null)
Like the rest of the type conversion functions in Terraform, explicit uses of tostring are not usually necessary because Terraform will perform implicit conversions where needed. The primary use of tostring is to normalize the types returned so that modules return consistent types of output.
11. type Function
The type function in Terraform is a very special function that is available only in the Terraform console command and not in normal Terraform configuration files. This is introduced in Terraform version 1.0 and later on.
type(value)
The purpose of the type function is to display the type of a given value, which can be useful in understanding type related error messages in your Terraform configuration.
For example
terraform console
> type("string")
string
> type(45)
number
> type(true)
bool
> type(null)
dynamic
12. try Function
The Terraform try function handles potential errors that might occur evaluating an expression. It evaluates the first expression. If the first expression does not produce any errors, the try function returns the result of the first expression. If the first expression produces an error, the try function evaluates the second expression and returns its result. The syntax is
try(expression1, expression2)
Therefore, it's only able to catch and handle errors that happen during runtime when data is being accessed or evaluated. It can't catch errors that Terraform is able to detect before runtime. Examples of such errors include Invalid syntax, Malformed resource references (Typing the wrong resource name, Using a resource that doesn't exist).
For example
local {
file-name = "example.txt"
}
resource "null_resource" "try" {
provisioner "local-exec" {
command = "echo '${try(tonumber(local.file_name),"No file found")}'"
}
}
Terraform will perform the following actions:
# module.executor.null_resource.module_executor will be created
+ resource "null_resource" "try" {
+ id = (known after apply)
}
Plan: 1 to add, 0 to change, 0 to destroy.
Enter a value: yes
module.executor.null_resource.try: Creating...
module.executor.null_resource.try: Provisioning with 'local-exec'...
module.executor.null_resource.try: Executing: ["/bin/sh" "-c" "echo 'No file found'"]
module.executor.null_resource.try: No file found
null_resource.try: Creation complete after 0s [id=4425172414869377883]
Related Pages
Feedback
Was this page helpful?