diff --git a/website/pages/docs/from-1.5/blocks/variable.mdx b/website/pages/docs/from-1.5/blocks/variable.mdx index e7af7093a..1b423ca6f 100644 --- a/website/pages/docs/from-1.5/blocks/variable.mdx +++ b/website/pages/docs/from-1.5/blocks/variable.mdx @@ -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/custom-validation.mdx'` + Example of a variable assignment from a file: `@include 'from-1.5/variables/foo-pkrvar.mdx'` diff --git a/website/pages/docs/from-1.5/variables.mdx b/website/pages/docs/from-1.5/variables.mdx index b22792667..73c5c3746 100644 --- a/website/pages/docs/from-1.5/variables.mdx +++ b/website/pages/docs/from-1.5/variables.mdx @@ -162,6 +162,8 @@ maintainers, use comments. The following sections describe these options in more detail. +`@include 'from-1.5/variables/custom-validation.mdx'` + ### Variables on the Command Line To specify individual variables on the command line, use the `-var` option when diff --git a/website/pages/partials/from-1.5/variables/custom-validation.mdx b/website/pages/partials/from-1.5/variables/custom-validation.mdx new file mode 100644 index 000000000..5a9757a0f --- /dev/null +++ b/website/pages/partials/from-1.5/variables/custom-validation.mdx @@ -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. \ No newline at end of file