I created a simple module with some variables, for example: Inside modules->network folder->main.tf:
(...)
provider "aws" {
region = var.aws_region
}
Inside the same folder, variables.tf :
variable "aws_region" {
type = string
default = "us-east-1"
}
(...)
Now when I call this module inside setup -> main.tf:
module "Network" {
source = "../modules/Network"
aws_region = ?
(...)
}
What can I put in the " aws_region = " to make it get the original default value of this variable? I know I can hard-code it or add another variables.tf file to the setups folder, but this is not good solution as I will need to maintain every variable in 2 locations..
Thx.
CodePudding user response:
actually I just figure this out - if you give it a default value in the module variable.tf file, there is no need to declare it at all under setups->main.tf. you can just write
module "Network" {
source = "../modules/Network"
}
And it will take all the default value for variables not called here
CodePudding user response:
The main way that Terraform uses default values for variables is if you omit the argument entirely when you call the module. The presence of a default
argument is what makes the argument optional:
module "network" {
source = "../modules/network"
}
There is one additional way you can make use of default values: if you change the declaration of the variable to include nullable = false
then Terraform will treat an explicit null
value the same as omitting the argument entirely.
Here's the updated declaration:
variable "aws_region" {
type = string
default = "us-east-1"
nullable = false
}
And then when you call the module, you can assign null
:
module "network" {
source = "../modules/network"
aws_region = null
}
By default, without nullable = false
, Terraform would literally set var.aws_region
to null
, but with this extra setting we tell Terraform to use the default value instead in that case.
Setting it directly to null
is not very useful since it's the same as omitting it entirely, but this extra behavior can be useful if you need to sometimes set the argument:
# Note: this is a different var.aws_region in the root
# module, _not_ the one inside the network module.
variable "aws_region" {
type = string
default = null
}
module "network" {
source = "../modules/network"
aws_region = var.aws_region
}
Notice that now there's an input variable aws_region
in the calling module too, but this one has default = null
which means that leaving it unset will cause it to be null
. I then passed that through to module "network"
directly, and because the module's own variable "aws_region"
has nullable = false
a null value would get automatically replaced with the default, without having to duplicate the default value in the calling module's declaration.