mac
mac

Reputation: 335

Terraform, how to pass variables to module using a variables file instead of repeating call

I'm passing variables to multiple modules using the code below. My questions is, is there a better way to do this? Perhaps a file with just the variables I'm passing to each module or a file that can be injected at run time. The code below works fine running from an Azure DevOps Pipeline, just trying to see if there was a simpler way to do the same with less lines of code.

Thanks,

======================================================

module network {
    source = "./Network"
    prdrgname = azurerm_resource_group.MYRG-AZ-EUS-MAIN-01.name
    prdlocation = azurerm_resource_group.MYRG-AZ-EUS-MAIN-01.location
    drrgname = azurerm_resource_group.MYRG-AZ-WUS-BC-01.name
    drlocation = azurerm_resource_group.MYRG-AZ-WUS-BC-01.location
}

module compute {    
    source = "./Compute"
    prdrgname = azurerm_resource_group.MYRG-AZ-EUS-MAIN-01.name
    prdlocation = azurerm_resource_group.MYRG-AZ-EUS-MAIN-01.location
    drrgname = azurerm_resource_group.MYRG-AZ-WUS-BC-01.name
    drlocation = azurerm_resource_group.MYRG-AZ-WUS-BC-01.location
}

============================================================

Upvotes: 0

Views: 2370

Answers (1)

Krismorte
Krismorte

Reputation: 632

I don't understand from where is coming azurerm_resource_group, if you could put your enterily code. But one of the best practices is use a .tfvars file

you will need a variables file like this

variable "name"{}
variable "location"{}
variable "name2"{}
variable "location2"{}

and the stage.tfvars or other name

name="value"
location="value"
name2="value"
location2="value"

you main.tf will be look like this

module network {
    source = "./Network"
    prdrgname = var.name
    prdlocation = var.location
    drrgname = var.name2
    drlocation = var.location2
}

module compute {    
    source = "./Compute"
    prdrgname = var.name
    prdlocation = var.location
    drrgname = var.name2
    drlocation = var.location2
}

and finally to run your project

terraform plan --var-file=stage.tfvars

Upvotes: 1

Related Questions