'How to validate a character set in terraform variable?

i need to validate a variable in terraform. The content of the variable should be only 0-9, a-z and A-Z. Im tried it with following code:

variable "application_name" {
    type = string
    default = "foo"

    validation {
    # regex(...) fails if it cannot find a match
    condition     = can(regex("([0-9A-Za-z])", var.application_name))
    error_message = "For the application_name value only a-z, A-Z and 0-9 are allowed."
  }
}

It doesen't work. When i set abcd- in the variable the validation returns true.

How can i fix the regex ?

Thanks for help ;)


@vgersh99 This doesn't work for me:

variable "application_name" {
    type = string
    default = "foo"

    validation {
    # regex(...) fails if it cannot find a match
    condition     = can(regex("[^[:alnum:]]", var.application_name))
    error_message = "For the application_name value only a-z, A-Z and 0-9 are allowed."
  }
}

Here is the error:

$ terraform validate
Error: Invalid value for variable
  on main.tf line 23, in module "ecs_cluster":
  23:   application_name = "frdlso"
For the application_name value only a-z, A-Z and 0-9 are allowed.
This was checked by the validation rule at
.terraform/modules/ecs_cluster/variables.tf:34,5-15


Solution 1:[1]

The regex function attempts to match a substring of the given string against the specified pattern, so the pattern in your first example will succeed as long as there is at least one ASCII digit or letter in the input.

To implement the rule you described you'll need to expand the pattern to cover the entire string. There are three parts of the regular expression syntax you can use together to achieve that:

  • The ^ symbol matches only at the start of the given string.
  • The $ symbol matches only at the end of the given string.
  • The + operator allows the preceding pattern to appear one or more times.

Putting those together, we get the pattern ^[0-9A-Za-z]+$: the beginning of the string, followed by one or more ASCII letters or digits, followed by the end of the string. This pattern will therefore only succeed if the entire string matches it.

Putting that into your full example gives us the following:

variable "application_name" {
    type = string
    default = "foo"

    validation {
    # regex(...) fails if it cannot find a match
    condition     = can(regex("^[0-9A-Za-z]+$", var.application_name))
    error_message = "For the application_name value only a-z, A-Z and 0-9 are allowed."
  }
}

Solution 2:[2]

Adding to Martin response there's also the shorthand [[:alnum:]] with the same behavior:

condition = can(regex("^[[:alnum:]]+$", var.application_name))

From the linked docs:

[[:alnum:]] The same as [0-9A-Za-z]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Martin Atkins
Solution 2 Evandro Pomatti