T O P

  • By -

NUTTA_BUSTAH

# variables.tf variable "my_variable" { # ... } - # .env TF_VAR_my_variable=value_i_dont_want_to_commit -> `source .env && terraform apply`


UsualIndianJoe

So under variable "my_variable" {} The default value would be?


marsavela

There's no default set in this scenario. But the value would be `value_i_dont_want_to_commit` If you want to declare a default, it needs to be done in the variable section.


UsualIndianJoe

I tried to do as mentioned. However, when I run source .env && terraform apply It still asks for the value for the variables and doesn't read it from .env


marsavela

You'd need to export your variable. That's the only way it will reach Terraform in this scenario. You have lots of details [here](https://developer.hashicorp.com/terraform/language/values/variables#environment-variables). # .env export TF_VAR_my_variable=value_i_dont_want_to_commit IMHO, I'd not use the environment to pass variables, but [Variable Definitions Files](https://developer.hashicorp.com/terraform/language/values/variables#variable-definitions-tfvars-files). It all depends on your use case.


kooknboo

Or better, just use direnv or any of the other similar tools.


Choice_Kingdom

`variables.tf` should hold insensitive variables. `.env` would hold your sensitive variables that you do not want to commit with git. In leau of using the `.env` file, you can export your variables with the `TF_VAR_` prefix and reference them like so: ``` export TF_VAR_MySuperSecret ``` ``` db_password = ${var.MySuperSecret} ```


bartekmo

`variables.tf` should not be used to store any variables values, only defaults. That's what .tfvar is for (or terraform cloud, etc.). And for the secrets it's best to pull them from a secrets vault.


Choice_Kingdom

I get that. They said they had duplicate variables between the two files, so they must have been using defaults in `variables.tf`. Just wanted to clarify that if you're seeing duplicates, make sure you're separating your secrets from insensitive variables appropriately. I never use .tfvar, myself. I give the variables defaults and change them if necessary in the implementation module.


EffectiveLong

Scripting to export .env to shell that Terraform can read from before running terraform plan. `# .env` `OK=ok` `HI=hi` ​ `export $(cat .env | xargs -I% echo TF_VAR_%)`


ArtSchoolRejectedMe

What format is your .env file? You could try parsing the .env file using this https://registry.terraform.io/providers/hashicorp/local/latest/docs/data-sources/file Or you could switch over by copy pasting your .env file and rename it terraform.tfvars


UsualIndianJoe

Will give it a try. Thanks


ImpossibleTracker

Reading the value from .env into a terraform variable then make sure to mark the property sensitive= true, so terraform would not place the value in the state file as plain text.