Terraform local env. variables vs cloud variables

508 Views Asked by At

I'm learning currently terraform and I found a situation which is not clear to me.

I've configured my TF project to use TF cloud to store state file. Obviously this is a good practice as I don't want to store the file locally. I have couple of variables which I would like to declare as env. variables; i.e. TF_VAR_region="xyz".

The problem is that when I want to use this variable tf plan is saying that variable is unknown (even if it is set locally). When I set the variable in the TF cloud workspace or as variable set assigned to the workspace. it works but it shows me:

│ Warning: Value for undeclared variable
│ 
│ The root module does not declare a variable named "region" but a value was
│ found in file
│ "/home/tfc-agent/.tfc-agent/component/terraform/runs/run-XXXX/terraform.tfvars".
│ If you meant to use this value, add a "variable" block to the
│ configuration.
│ 
│ To silence these warnings, use TF_VAR_... environment variables to provide
│ certain "global" settings to all configurations in your organization. To
│ reduce the verbosity of these warnings, use the -compact-warnings option.

I don't want to set variables in variables.tf file because one of those variables is sensitive and I don't want to commit it into the repository. Also I kind of don't want to declare manually variables in TF cloud since, ... well it's manual activity where I can just forget that I have set something somewhere. It would be better for me to have everything in "one place" so to speak (i.e. in readme I would have description that I have to set env variables for the process to work).

Is there a way how can I use TF cloud to store state file but at the same time be able to use local variables? i.e. when running localy terraform apply.

1

There are 1 best solutions below

1
On BEST ANSWER

You don't have to set variable values inside variables.tf file

variable "var_name" {
  description = "Secret variable"
  type        = string
  sensitive   = true
}

terraform will prompt you to set variable value if it didn't set else where:

$ terraform plan

var.var_name
  Secret variable

  Enter a value:

In other way defining of variable inside configuration is a good style and clearly describing terraform what variables should be set before plan or apply

well it's manual activity where I can just forget that I have set something somewhere

And that is one more reason to define variable inside configuration. terraform will raise error if you forget to set something that is describing in configuration somewhere. Because error is easier to debug than silence

Here is an article about variables that may be helpful