I'm building a lambda function on aws with terraform. The syntax within the terraform script for uploading an env var is:
resource "aws_lambda_function" "name_of_function" {
...
environment {
variables = {
foo = "bar"
}
}
}
Now I have a .env
file in my repo with a bunch of variables, e.g. email='[email protected]'
, and I'd like terraform to read (some of) them from that file and inject them into the space for env vars to be uploaded and available to the lambda function. How can this be done?
Use Case. Terraform can directly access environment variables that are named using the pattern TF_VAR_ , for example TF_VAR_foo=bar will provide the value bar to the variable declared using variable "foo" {} .
The load_dotenv method from dotenv provides the functionality to read data from a . env file. You do not need to install the os package as it's built into Python.
On the Projects page, select the project that you want to import environment variables to, and click Properties to open the Project Properties window. On the General page, click Environment. In the Environment Variables dialog, click Import from File.
This is a pure TerraForm-only solution that parses the .env
file into a native TerraForm map.
output "foo" {
value = { for tuple in regexall("(.*)=(.*)", file("/path/to/.env")) : tuple[0] => tuple[1] }
}
I have defined it as an output to do quick tests via CLI but you can always define it as a local or directly on an argument.
My solution for now involves 3 steps.
export TF_VAR_FOO=bar
Yes, it's slightly annoying that you HAVE TO prefix your vars with TF_VAR_
, but I've learned to live with it (at least it makes it clear in your .env what vars will be used by terraform, and which will not.)
TF_VAR_
prefix. E.g.variable "FOO" {
description = "Optionally say something about this variable"
}
. .env
) so that any such variable is available to processes you want to launch in your present shell environment (viz. terraform here). Adding this step doesn't bother me since I always operate my repo with bash scripts anyway.Note: I put in a request for a better way to handle .env files here though I'm actually now quite happy with things as is (it was just poorly described in the official documentation how TF relates to .env files IMO).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With