1
votes

Trying my hand at terraform modules and running into a weird issue (I think). Here's my structure: [TF directory structure.][1] [1]: https://i.stack.imgur.com/P4fyr.png

Here's the root main.tf:

    provider "azurerm" {
      features {
      }
    }
   
    module "createrg" {
      source = "./modules/rg"
      my_loc = var.my_loc
      rgName = var.rgName
    }

Here's the root variables.tf

    variable "my_loc" {
      type = "string"
    }
    
    variable "rgName" {
      type = "string"
    }

here's the main.tf for the "rg" module:

    provider "azurerm" {
      ## dev_subscription_id = var.dev_subscription
      features {
        
      }
    }
    resource "azurerm_resource_group" "rgDev" {
      location = var.my_loc
      name = var.rgName
    }

and here's the variable.tf for the "rg" module

    variable "my_loc" {
      type = "string"
    }
    
    variable "rgName" {
      type = "string"
    }

here's the dev.tfvars

    my_loc = "canadacentral"
    rgName = "rg_ModuleTest"

I run the plan as:

terraform plan -var-file=./variables/dev.tfvars

Since I just got started with terraform, I'm using the latest version. If I remove any of the variables from either one or both variables.tf, I get errors and the plan doesn't execute. For example if I remove a variable declaration from the root variables.tf file, I get the error: "Error: Reference to undeclared input variable" and if I remove the variable declaration from the variable.tf in the rg module, I get an error: "Error: Unsupported argument... An argument named "rgName" is not expected here." The only way the plan works is when I have the same variables in the variables.tf file of both the root and the rg module.

Is this how modules are supposed to work? I've scoured the internet for an explanation but I think I'm missing something here. I mean, if I have modules to create for 20 resources, it feels absurd to think I have to replicate variables in both places - root and the respective module's variables.tf file.

Thank you in advance for your help.

1

1 Answers

2
votes

Modules are self-contained. All the variables required to successfully execute your rg module are defined in ./modules/rg/variables.tf.

Since you haven't defined any default values for them, they are unitialized. Thus in your root main.tf, when you are creating your createrg module you have to explicitly set all these variables.

Regarding the naming, in your '.root/main', your varibles var.my_loc and var.rgName don't need to have same names as those in the ./modules/rg/variables.tf. They can have any names or be constants, as long as your are going to set all these uninitialized variables of your module.