CodexBloom - Programming Q&A Platform

Terraform scenarios to Read Local Variables from Environment Files in Different Workspaces

👀 Views: 49 đŸ’Ŧ Answers: 1 📅 Created: 2025-07-24
terraform workspace variables hcl

I've been working on this all day and I'm deploying to production and This might be a silly question, but I'm having trouble with Terraform where it seems to ignore local variables defined in `.tfvars` files when switching between workspaces... I have a project that uses Terraform 1.4.5, and I'm trying to manage different environments (dev, staging, production) using workspaces. I've defined my variables in a `variables.tf` file, and I also have separate environment-specific `.tfvars` files such as `dev.tfvars` and `prod.tfvars`. Here's a snippet of how I structure my variables in `variables.tf`: ```hcl variable "instance_type" { description = "EC2 instance type" type = string default = "t2.micro" } ``` In my `dev.tfvars`, I specify: ```hcl instance_type = "t2.medium" ``` And I run Terraform commands like this: ```bash tf workspace select dev tf apply -var-file=dev.tfvars ``` Despite this, Terraform keeps applying the default value of `t2.micro` for the `instance_type` variable when I run `terraform apply`. I also tried setting the variable directly in the CLI with `-var 'instance_type=t2.medium'`, but I get a warning about the variable being overwritten. It seems like the `.tfvars` file isn't being respected in this context. I've confirmed that I'm in the correct workspace using `terraform workspace show`, and I can see the environment variable content using `terraform vars` command. Can anyone suggest what might be going wrong or how to ensure that the `.tfvars` file is read correctly while using workspaces? I've been using Hcl for about a year now. Thanks in advance!