Passing in arguments to a module

I have a module the config file for this are in module/mymodule, in the directory that is the parent of the module directory I have a file with a module block and a source line, I want to pass an argument into the module - this is straight forward, however if I want the argument to take the value of an environment variable, how do I do this ?

Hi @chrisadkin,

A Terraform configuration can’t access environment variables directly. Instead, you’d need to declare an input variable to the root module and, if it’s still convenient to source the value from an environment variable, assign that on the command line:

terraform plan -var="example=$ENV_VARIABLE"

Although a Terraform configuration can’t directly access environment variables itself, the Terraform CLI does support specially-named environment variables as an alternative to this -var option, so an alternative way to get the same result as the above would be to set an environment variable named TV_VAR_example, which Terraform will understand as a value for the variable "example" declared in the root module.

Although the core Terraform language doesn’t interact directly with environment variables, I see that there’s a community provider clockworksoul/env which treats environment variables as external data retrievable via a data source. I’ve not used that provider directly myself so I can’t vouch for its behavior but it might perhaps offer an alternative solution to your problem, if using an already-existing environment variable is a hard requirement.

1 Like