地形。如何使用 variable.tf 文件中的列表(字符串)在命令行中传递多个值?

Terraform . How to pass multiple values in command line using list (string) in variable.tf file?

我有一个简单的主文件和变量文件,用于在 Azure 中为容器部署 webapp。

但我希望 terraform plan 使用命令行中的变量来选择如下名称:

terraform plan -var resource_group_name=my-rg

像这样评论 RG 默认值的名称非常有效。

main.tf

data "azurerm_resource_group" "my-rg" {
  name = var.resource_group_name
}

variable.tf

variable "resource_group_name" {

    
#    default = "Search-API"

}

但是如果我想对列表字符串执行相同的操作,我不知道该怎么做。我希望能够做一些事情,如果我输入 2 个名称,将创建 2 个 webapps,如果我输入 3、3 个 webapps 等等。

我试过这个(也评论了默认值):

main.tf

resource "azurerm_app_service" "azure-webapp" {
  count = length(var.webapp_server_name)
  name  = var.webapp_server_name[count.index]

variable.tf

variable "webapp_server_name" {
  
    description = "Create Webapp with following names"
    type        = list(string)
    #default     = ["webapp-a", "webapp-b", "webapp-c"]

但我得到:

 terraform plan -var webapp_server_name=webapp-a

Error: Variables not allowed

  on <value for var.webapp_server_name> line 1:
  (source code not available)

Variables may not be used here.

我也尝试过使用空字符串,例如:

variable "webapp_server_name" {
  
    description = "Create Webapp with following names"
    type        = list(string)
    default     = []
}

有没有办法用 terraform 做这样的事情?定义一个空列表并从命令传递值(一个、两个或更多)?

谢谢


更新 像这样尝试过,按照 但现在要求输入值,即使我通过命令行传递它

terraform plan -var 'listvar=["webapp-a"]'

var.webapp_server_name
  Create Webapp with following names

  Enter a value:

当您使用 -var webapp_server_name=webapp-a 从命令行传入变量时,您将其作为字符串传入。

但您已将变量定义为列表。所以基于 the docs 你会希望命令行看起来像这样:

terraform plan -var='webapp_server_name=["webapp-a"]'

如果有变量声明:

variable "webapp_server_name" {
  
    description = "Create Webapp with following names"
    type        = list(string)
    #default     = ["webapp-a", "webapp-b", "webapp-c"]
}

您可以将它与 \ 一起使用以转义引号 ".

terraform plan -var 'webapp_server_name=[\"webapp-a\", \"webapp-b\", \"webapp-c\"]'

例如,它使用最新的 terraform 提供程序版本 Terraform v0.13.4