Hello Team,
I have tried to set up an environment variable. It works in a normal directory. Say for E.g.,
TF_VAR_instancetype = t2.small
Executing a plan from a main directory works as expected.
When the same block is invoked as a part of a module, variable throws an error as not declared. any suggestions ?
Could you explain a bit more about what you are doing?
Is this correct? You have a root module with a variable called “instancetype” and you also have a submodule used by that root module?
@stuart-c , I wanted to use environment variables in the sub module.
E.g., I have a folder structure like below:
Modules:
Modules>EC2 > ec2.tf
In ec2.tf of a root module, I have defined and declared a variable.
variable instancetype {}
resource “aws_instance” “ABC”{
ami = “ami-XXXX”
instance_type = var.instancetype
}
Under a project:
Project> Project-Dev >devec2.tf
Under devec2.tf
module “ec2module” {
source = “…/…/modules/ec2”
}
I have defined an environment variable of instancetype=t2.small
I am able to check and verify from the terminal through echo%TF_VAR_instancetype% which results in t2.small
From the Terminal now:
Project> Project-Dev > from this location (sub module) when I execute the plan, it is unable to get the definition of the environment variable. Throws up an error.
Whereas when i execute the plan from root module Modules>EC2 >
instancetype value gets fetched from environment variable and works as expected.
Any reason why in sub module, environment variable is not getting identified? what is the workaround from sub module to get the values of environment variable?
Thanks.
The environment variables are just used by variables configured in the root module.
If you want a value from an environment variable to be used by a module you would:
- Create a root module variable
- Pass that variable’s content to your module (ie. use var.variable_name in the module instance definition)
- Set the environment variable when running Terraform
1 Like