github.com/hashicorp/packer@v1.14.3/website/content/partials/from-1.5/variables/custom-validation.mdx (about) 1 ### Custom Validation Rules 2 3 [inpage-validation]: #custom-validation-rules 4 5 In addition to Type Constraints, you can specify arbitrary custom validation 6 rules for a particular variable using one or more `validation` block nested 7 within the corresponding `variable` block: 8 9 ```hcl 10 variable "image_id" { 11 type = string 12 description = "The ID of the machine image (AMI) to use for the server." 13 14 validation { 15 condition = length(var.image_id) > 4 && substr(var.image_id, 0, 4) == "ami-" 16 error_message = "The image_id value must be a valid AMI ID, starting with \"ami-\"." 17 } 18 } 19 ``` 20 21 The `condition` argument is an expression that must use the value of the 22 variable to return `true` if the value is valid or `false` if it is invalid. 23 The expression can refer only to the variable that the condition applies to, 24 and _must not_ produce errors. 25 26 If the failure of an expression is the basis of the validation decision, use 27 [the `can` function](/packer/docs/templates/hcl_templates/functions/conversion/can) to detect such errors. For example: 28 29 ```hcl 30 variable "image_id" { 31 type = string 32 description = "The ID of the machine image (AMI) to use for the server." 33 34 validation { 35 # regex(...) fails if it cannot find a match 36 condition = can(regex("^ami-", var.image_id)) 37 error_message = "The image_id value must be a valid AMI ID, starting with \"ami-\"." 38 } 39 } 40 ``` 41 42 If `condition` evaluates to `false`, an error message including the sentences 43 given in `error_message` will be produced. The error message string should be 44 at least one full sentence explaining the constraint that failed, using a 45 sentence structure similar to the above examples. 46 47 Validation also works with more complex cases: 48 49 ```hcl 50 variable "image_metadata" { 51 52 default = { 53 key: "value", 54 something: { 55 foo: "bar", 56 } 57 } 58 59 validation { 60 condition = length(var.image_metadata.key) > 4 61 error_message = "The image_metadata.key field must be more than 4 runes." 62 } 63 64 validation { 65 condition = can(var.image_metadata.something.foo) 66 error_message = "The image_metadata.something.foo field must exist." 67 } 68 69 validation { 70 condition = substr(var.image_metadata.something.foo, 0, 3) == "bar" 71 error_message = "The image_metadata.something.foo field must start with \"bar\"." 72 } 73 74 } 75 ```