github.com/iaas-resource-provision/iaas-rpc@v1.0.7-0.20211021023331-ed21f798c408/website/docs/language/expressions/conditionals.html.md (about) 1 --- 2 layout: "language" 3 page_title: "Conditional Expressions - Configuration Language" 4 --- 5 6 # Conditional Expressions 7 8 > **Hands-on:** Try the [Create Dynamic Expressions](https://learn.hashicorp.com/tutorials/terraform/expressions?in=terraform/configuration-language&utm_source=WEBSITE&utm_medium=WEB_IO&utm_offer=ARTICLE_PAGE&utm_content=DOCS) tutorial on HashiCorp Learn. 9 10 A _conditional expression_ uses the value of a bool expression to select one of 11 two values. 12 13 The syntax of a conditional expression is as follows: 14 15 ```hcl 16 condition ? true_val : false_val 17 ``` 18 19 If `condition` is `true` then the result is `true_val`. If `condition` is 20 `false` then the result is `false_val`. 21 22 A common use of conditional expressions is to define defaults to replace 23 invalid values: 24 25 ``` 26 var.a != "" ? var.a : "default-a" 27 ``` 28 29 If `var.a` is an empty string then the result is `"default-a"`, but otherwise 30 it is the actual value of `var.a`. 31 32 ## Conditions 33 34 The condition can be any expression that resolves to a boolean value. This will 35 usually be an expression that uses the equality, comparison, or logical 36 operators. 37 38 ## Result Types 39 40 The two result values may be of any type, but they must both 41 be of the _same_ type so that Terraform can determine what type the whole 42 conditional expression will return without knowing the condition value. 43 44 If the two result expressions don't produce the same type then Terraform will 45 attempt to find a type that they can both convert to, and make those 46 conversions automatically if so. 47 48 For example, the following expression is valid and will always return a string, 49 because in Terraform all numbers can convert automatically to a string using 50 decimal digits: 51 52 ```hcl 53 var.example ? 12 : "hello" 54 ``` 55 56 Relying on this automatic conversion behavior can be confusing for those who 57 are not familiar with Terraform's conversion rules though, so we recommend 58 being explicit using type conversion functions in any situation where there may 59 be some uncertainty about the expected result type. 60 61 The following example is contrived because it would be easier to write the 62 constant `"12"` instead of the type conversion in this case, but shows how to 63 use [`tostring`](/docs/language/functions/tostring.html) to explicitly convert a number to 64 a string. 65 66 ```hcl 67 var.example ? tostring(12) : "hello" 68 ```