github.com/muratcelep/terraform@v1.1.0-beta2-not-internal-4/website/docs/language/functions/can.html.md (about) 1 --- 2 layout: "language" 3 page_title: "can - Functions - Configuration Language" 4 sidebar_current: "docs-funcs-conversion-can" 5 description: |- 6 The can function tries to evaluate an expression given as an argument and 7 indicates whether the evaluation succeeded. 8 --- 9 10 # `can` Function 11 12 `can` evaluates the given expression and returns a boolean value indicating 13 whether the expression produced a result without any errors. 14 15 This is a special function that is able to catch errors produced when evaluating 16 its argument. For most situations where you could use `can` it's better to use 17 [`try`](./try.html) instead, because it allows for more concise definition of 18 fallback values for failing expressions. 19 20 The primary purpose of `can` is to turn an error condition into a boolean 21 validation result when writing 22 [custom variable validation rules](/docs/language/values/variables.html#custom-validation-rules). 23 For example: 24 25 ``` 26 variable "timestamp" { 27 type = string 28 29 validation { 30 # formatdate fails if the second argument is not a valid timestamp 31 condition = can(formatdate("", var.timestamp)) 32 error_message = "The timestamp argument requires a valid RFC 3339 timestamp." 33 } 34 } 35 ``` 36 37 The `can` function can only catch and handle _dynamic_ errors resulting from 38 access to data that isn't known until runtime. It will not catch errors 39 relating to expressions that can be proven to be invalid for any input, such 40 as a malformed resource reference. 41 42 ~> **Warning:** The `can` function is intended only for simple tests in 43 variable validation rules. Although it can technically accept any sort of 44 expression and be used elsewhere in the configuration, we recommend against 45 using it in other contexts. For error handling elsewhere in the configuration, 46 prefer to use [`try`](./try.html). 47 48 ## Examples 49 50 ``` 51 > local.foo 52 { 53 "bar" = "baz" 54 } 55 > can(local.foo.bar) 56 true 57 > can(local.foo.boop) 58 false 59 ``` 60 61 The `can` function will _not_ catch errors relating to constructs that are 62 provably invalid even before dynamic expression evaluation, such as a malformed 63 reference or a reference to a top-level object that has not been declared: 64 65 ``` 66 > can(local.nonexist) 67 68 Error: Reference to undeclared local value 69 70 A local value with the name "nonexist" has not been declared. 71 ``` 72 73 ## Related Functions 74 75 * [`try`](./try.html), which tries evaluating a sequence of expressions and 76 returns the result of the first one that succeeds.