I want to validate that the value passed to a variable conforms to a naming convention, and I want to define that naming convention using a regular expression. Here is a contrived example that uses terraform’s check block:
variable "s3_bucket_name" {
description = "S3 bucket name"
type = string
}
check "s3_bucket_name" {
assert {
# Check that the value is some alpabetic charcters followed by some digits
condition = regex("[a-z]+[0-9]+", var.s3_bucket_name)
error_message = "s3_bucket_name does not match naming convention"
}
}
If I run
terraform plan --var s3_bucket_name=abc123
I get an error:
Invalid condition result value: a bool is required.
If I run
terraform plan --var s3_bucket_name=123abc
I get an error:
Call to function “regex” failed: pattern did not match any part of the given string.
I understand why this is the case, the first one fails because regex()
doesn’t return a boolean. The second one fails because regex()
throws an error.
This behaviour isn’t helpful to me though. How can I use a check to put a warning into the plan if the supplied value does not conform to a regular expression?