carl
carl

Reputation: 396

count with an input from user in Terraform?

I want to create a number of resources using terraform depending which number the user enters. The number have to be between 2 and 5. I tried: in vars.tf:

variable "user_count" {
    type = number
    default = 2
    description = "How many number of VMs to create (minimum 2 and no more than 5): "
}

The problem here is its creates the resources with the default number 2.

Another case:

variable "user_count" {
        type = number
        description = "How many number of VMs to create (minimum 2 and no more than 5): "
    }

Here, without the default parameter. I get the message/description, but I/the user can enter anything! How to make this possible? - the user get a message and verify the number is between 2 and 5, else the resources will not be created.

Any help is appreciate - I am really stuck in it!

Upvotes: 0

Views: 310

Answers (1)

Krzysztof Madej
Krzysztof Madej

Reputation: 40829

You may try custom validation

variable "user_count" {
        type = number
        description = "How many number of VMs to create (minimum 2 and no more than 5): "
        validation {
          condition     = var.user_count > 1 && var.user_count < 6
          error_message = "Validation condition of the user_count variable did not meet."
        }
}

But maybe better option instead of checking number, will be variable as string and regex to check if value is 2,3,4 or 5.

variable "user_count" {
  type        = string
  description = "How many number of VMs to create (minimum 2 and no more than 5): "

  validation {
    # regex(...) fails if it cannot find a match
    condition     = can(regex("2|3|4|5", var.user_count))
    error_message = "Validation condition of the user_count variable did not meet."
  }
}

Upvotes: 2

Related Questions