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