Can Terraform reuse variables already manually entered?

I think it’s really handy how terraform prompts for variables with a description that don’t have defined values. I was however hoping though, that once an apply has been successful it would be handy if the undefined variables that were entered were automatically reused.

I know that people can make scripts to define env vars, but this isn’t the same and not as portable, and I thought it would be great if these prompts could recall previous values where possible.

There may be some exceptions to that, like a secret key, but it would be possible to handle vars differently based on some tag if that were a problem.

Hi @queglay

This feels like it is best handled by using a .tfvars file to set the variables for the local computer, which you can then pass directly into your terraform apply command (e.g., terraform apply -var-file=sample.tfvars. Documentation can be found here.

I would recommend not committing any .tfvars files into source control, as a point of clarification. Instead, keeping them local to the machine that is running the terraform apply.

I’m familiar with them. I was kind of hoping for better behaviour from the prompts to persist. It’s also doubly weird that during terraform destroy you will get prompted again for vars you’ve already defined and are about to become no longer relevant.

It’s also problematic that the prompts will result in a deployment that cannot necessarily be modified safely if you forget what was entered last time. tf vars are great but they are not interactive like the prompts are and it would be great if they could be better by optionally persisting to a backend (perhaps with a flag).

I’m sure something could be done to write outputs to s3 backend encrypted and read them back in elsewhere I guess, though thats a little clunky and turns something that could be a dingle stage into a few, and means replacing vars with data resources in .tf files

Personally I solely use tfvars files to supply variables and if I see any prompts I see that as a mistake where I’ve missed specifying one. Also, as fetch all secrets directly from Vault (and therefore have nothing sensitive in the tfvars) we commit them into git, meaning we then don’t have the issue about forgetting/not knowing what has been previously used.

In terms of having something that created a tfvars file if you entered details, I could see that being able to be implemented by a wrapper script. I’ve no idea if such a thing currently exists, but it probably wouldn’t be too difficult to implement in the language of your choice.

1 Like