terraform - 从命令行为模块变量设置变量

terraform - set a variable from commandline for module variable

我有以下结构

main.tf
modules
--moduleA
----worker.tf
----variables.tf

main.tf的内容:

module "moduleA" {
  source = "./modules/moduleA"
}

variables.tf的内容:

variable "num_of_workers" {
  type        = number
  description = "This is number of workers"
  default     = 1

我要共同通话terraform apply var="num_of_workers=12" 我收到一个错误:

Error: Value for undeclared variable
│ A variable named "num_of_workers" was assigned on the command line, but the root module does not declare a variable of that name. To use this value, add a "variable" block to the configuration.

有没有办法在模块中设置 variables.tf 中的变量并从命令行设置它们?我在这里缺少什么?

您可以从命令行分配一个变量,如下所示:

terraform apply -var num_of_workers=2

或者像这样:

terraform apply -var 'num_of_workers=2'

参考:Terraform docs

您还需要在父级声明变量。然后你会像这样将父级值传递给模块:

variable "num_of_workers" {
  type = number
}

module "moduleA" {
  source = "./modules/moduleA"
  num_of_workers = var.num_of_workers
}

然后您可以在命令行中设置父级值,如下所示:

terraform apply -var num_of_workers=2