Files
Packer-Cn/website/content/partials/from-1.5/variables/custom-validation.mdx
50da6c8dc8 docs: Migrate link formats (#12192)
* Adding check-legacy-links-format workflow

* Adding test-link-rewrites workflow

* Migrating links to new format

* Updating docs-content-check-legacy-links-format hash

* chore: update source

* Update generated partials from Packer plugin SDK

* Bump packer-plugin-sdk to get latest packer-sdc

* Update website/content/docs/templates/hcl_templates/blocks/build/provisioner.mdx

* Update Plugin SDK to fix shell-local regression

---------

Co-authored-by: Kendall Strautman <[email protected]>
Co-authored-by: Wilken Rivera <[email protected]>
Co-authored-by: Kendall Strautman <[email protected]>
2023-01-27 09:47:08 -08:00

76 lines
2.3 KiB
Plaintext

### Custom Validation Rules
[inpage-validation]: #custom-validation-rules
In addition to Type Constraints, you can specify arbitrary custom validation
rules for a particular variable using one or more `validation` block nested
within the corresponding `variable` block:
```hcl
variable "image_id" {
type = string
description = "The ID of the machine image (AMI) to use for the server."
validation {
condition = length(var.image_id) > 4 && substr(var.image_id, 0, 4) == "ami-"
error_message = "The image_id value must be a valid AMI ID, starting with \"ami-\"."
}
}
```
The `condition` argument is an expression that must use the value of the
variable to return `true` if the value is valid or `false` if it is invalid.
The expression can refer only to the variable that the condition applies to,
and _must not_ produce errors.
If the failure of an expression is the basis of the validation decision, use
[the `can` function](/packer/docs/templates/hcl_templates/functions/conversion/can) to detect such errors. For example:
```hcl
variable "image_id" {
type = string
description = "The ID of the machine image (AMI) to use for the server."
validation {
# regex(...) fails if it cannot find a match
condition = can(regex("^ami-", var.image_id))
error_message = "The image_id value must be a valid AMI ID, starting with \"ami-\"."
}
}
```
If `condition` evaluates to `false`, an error message including the sentences
given in `error_message` will be produced. The error message string should be
at least one full sentence explaining the constraint that failed, using a
sentence structure similar to the above examples.
Validation also works with more complex cases:
```hcl
variable "image_metadata" {
default = {
key: "value",
something: {
foo: "bar",
}
}
validation {
condition = length(var.image_metadata.key) > 4
error_message = "The image_metadata.key field must be more than 4 runes."
}
validation {
condition = can(var.image_metadata.something.foo)
error_message = "The image_metadata.something.foo field must exist."
}
validation {
condition = substr(var.image_metadata.something.foo, 0, 3) == "bar"
error_message = "The image_metadata.something.foo field must start with \"bar\"."
}
}
```