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