How can I use regex in a terraform check?

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.

image

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.

image

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?

1 Like

OK, I found the answer. function can (can - Functions - Configuration Language | Terraform | HashiCorp Developer) is the thing to use:

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     = can(regex("[a-z]+[0-9]+", var.s3_bucket_name))
    error_message = "s3_bucket_name does not match naming convention"
  }
}

When you pass something that matches the regex:

When you pass something that does not match the regex: