首页 > 解决方案 > 在 Terraform 中计算用户的输入?

问题描述

我想根据用户输入的数字使用 terraform 创建许多资源。数字必须在 2 到 5 之间。我试过:在vars.tf

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

这里的问题是它创建了默认编号为 2 的资源。

另一个案例:

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

在这里,没有默认参数。我收到消息/描述,但我/用户可以输入任何内容!如何使这成为可能?- 用户收到消息并验证数字在 2 到 5 之间,否则将不会创建资源。

感谢您提供任何帮助-我真的陷入了困境!

标签: azure-devopsterraform

解决方案


您可以尝试自定义验证

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."
        }
}

但也许更好的选择而不是检查数字,将可变为字符串和正则表达式来检查值是 2、3、4 还是 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."
  }
}

推荐阅读