Is there any way to load secret credentails from .env instead of .tfvars file?

compartment_id=“XXX” in .env file

Than variables.tf as:

locals {
  envs = { for tuple in regexall("(.*)=(.*)", file(".env")) : tuple[0] => sensitive(tuple[1]) }
}
output "envs" { value = envs }

variable "compartment_id" {
  type = string
}

outputs.tf as follows:

output "compartment_id" {
  description = "Compartment in which scripts are getting executed"
  value       = var.compartment_id
}

When i run terraform outputs compartment_id it gives warning with no output values present. I’m new to terraform so help me solve the errors.

Why instead store secret values in .env values without any encryption, you use secret store like vault or secrets manager (AWS) ? can you share more about this environment?

By .env I assume you mean a file that defines some environment variables which you then source into your environment yourself or have some other tooling which does so. Terraform won’t read that file directly, but can use environment variables to load variable data, and those TF_VAR_ definitions could be stored in your env file.

1 Like

Interesting trick. I can see scenarios when this would be useful, though agree with above that it’s probably not a great practice in most cases.

You’ll need to parse out the quote marks a little more carefully.

You wouldn’t be able to set a variable to the value, but your thing basically works with a little modification:

% cat test.tf
locals {
  envs = {
    for tuple in regexall("(?m)^(\\S+)=\"?([^\"]+)\"?$", file(".env")) : tuple[0] => tuple[1]
  }
}

output "envs" {
  value = local.envs
}
% cat .env   
foo="bar"
baz="bala"
qux=asdf12345
qux2="asdf12345"
% tf apply

No changes. Your infrastructure matches the configuration.

Terraform has compared your real infrastructure against your configuration and found no
differences, so no changes are needed.

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

envs = {
  "baz" = "bala"
  "foo" = "bar"
  "qux" = "asdf12345"
  "qux2" = "asdf12345"
}

(I removed the sensitive() call just so that I could view the output, but you should add it back if you were to actually do something like this).

1 Like