terraformterraform-provider-azure

terraform - set a variable from commandline for module variable


I have following structure

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

Content of main.tf:

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

Content of variables.tf:

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

I want co call terraform apply var="num_of_workers=12" I am getting an error:

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.

Is there any way to set variables in variables.tf in module and set them from commandline? What I am missing here?


Solution

  • You need to also declare the variable at the parent level. Then you would pass the parent level value to the module like this:

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

    Then you would set the parent-level value at the command line like this:

    terraform apply -var num_of_workers=2
    

    Documentation: https://developer.hashicorp.com/terraform/language/values/variables