This commit is contained in:
Adrien Delorme 2020-11-02 17:20:46 +01:00
parent 88175873e5
commit d919fc28ab
3 changed files with 47 additions and 0 deletions

View File

@ -24,6 +24,8 @@ If a default value is set, the variable is optional. Otherwise, the variable
`@include 'from-1.5/variables/assignment.mdx'` `@include 'from-1.5/variables/assignment.mdx'`
`@include 'from-1.5/variables/custom-validation.mdx'`
Example of a variable assignment from a file: Example of a variable assignment from a file:
`@include 'from-1.5/variables/foo-pkrvar.mdx'` `@include 'from-1.5/variables/foo-pkrvar.mdx'`

View File

@ -162,6 +162,8 @@ maintainers, use comments.
The following sections describe these options in more detail. The following sections describe these options in more detail.
`@include 'from-1.5/variables/custom-validation.mdx'`
### Variables on the Command Line ### Variables on the Command Line
To specify individual variables on the command line, use the `-var` option when To specify individual variables on the command line, use the `-var` option when

View File

@ -0,0 +1,43 @@
## 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](./functions/can.html) 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.