I am using terraform check block to check whether the environment provided by user matches the selected workspace. When I do apply or plan, I do see that assertion check has failed (for mismatched values) but it doesn’t throw an error. Is there a way to raise an error when the assertion check fails. My idea is to halt plan or apply operation if the provided environment doesn’t match the selected workspace before proceeding to apply/check for other resources.
variable "env" {
type = string
validation {
condition = contains(["dev", "staging", "pre-prod", "prod"], var.env)
error_message = "env must be one of dev | staging | pre-prod | prod"
}
}
check "validate_env" {
assert {
condition = var.env == terraform.workspace
error_message = "environment and terraform workspace do not match"
}
}
This produces following warning message:
❯ terraform apply
var.env
Enter a value: prod
No changes. Your infrastructure matches the configuration.
Terraform has compared your real infrastructure against your configuration and found no
differences, so no changes are needed.
╷
│ Warning: Check block assertion failed
│
│ on main.tf line 20, in check "validate_env":
│ 20: condition = var.env == terraform.workspace
│ ├────────────────
│ │ terraform.workspace is "dev"
│ │ var.env is "prod"
│
│ environment and terraform workspace do not match
╵
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.