Home Explore Blog CI



docker

2nd chunk of `content/manuals/build/bake/variables.md`
991a3402a5f1fa5fb893783b649e18df17a11dbf2d78f5c400000001000008f0
    error_message = "The variable 'PORT' must be 1024 or higher."  # Error message for invalid values
  }
}
```

If the `condition` expression evaluates to `false`, the variable value is
considered invalid, whereby the build invocation fails and `error_message` is
emitted. For example, if `PORT=443`, the condition evaluates to `false`, and
the error is raised.

Values are coerced into the expected type before the validation is set. This
ensures that any overrides set with environment variables work as expected.

### Validate multiple conditions

To evaluate more than one condition, define multiple `validation` blocks for
the variable. All conditions must be `true`.

Here’s an example:

```hcl {title=docker-bake.hcl}
# Define a variable `VAR` with multiple validation rules
variable "VAR" {
  # First validation block: Ensure the variable is not empty
  validation {
    condition = VAR != ""
    error_message = "The variable 'VAR' must not be empty."
  }

  # Second validation block: Ensure the value contains only alphanumeric characters
  validation {
    # VAR and the regex match must be identical:
    condition = VAR == regex("[a-zA-Z0-9]+", VAR)
    error_message = "The variable 'VAR' can only contain letters and numbers."
  }
}
```

This example enforces:

- The variable must not be empty.
- The variable must match a specific character set.

For invalid inputs like `VAR="hello@world"`, the validation would fail.

### Validating variable dependencies

You can reference other Bake variables in your condition expression, enabling
validations that enforce dependencies between variables. This ensures that
dependent variables are set correctly before proceeding.

Here’s an example:

```hcl {title=docker-bake.hcl}
# Define a variable `FOO`
variable "FOO" {}

# Define a variable `BAR` with a validation rule that references `FOO`
variable "BAR" {
  # Validation block to ensure `FOO` is set if `BAR` is used
  validation {
    condition = FOO != ""  # Check if `FOO` is not an empty string
    error_message = "The variable 'BAR' requires 'FOO' to be set."
  }
}
```

This configuration ensures that the `BAR` variable can only be used if `FOO`
has been assigned a non-empty value. Attempting to build without setting `FOO`
will trigger the validation error.

Title: Validating Variables: Multiple Conditions and Dependencies
Summary
This section explains how to validate variables in Bake using multiple validation blocks and how to validate dependencies between variables. It demonstrates how to define multiple `validation` blocks to enforce multiple conditions on a variable and how to reference other variables in validation conditions to ensure dependencies are met.