Single local file for environment

Hi guys,

Is it possible to have single local.tf file for all Terraform environment for example “testing”? I mean the infrastructure as below:

Infra
–prod
– locals.tf
–terrraform files…
–dev
– locals.tf
–terrraform files…
–qa
– locals.tf
–terrraform file…

I know this can be achieved with variables but my colleagues thing this way might be a little bit more secure.

Regards,
Ivo

If I’m understanding correctly, you’re trying to share Terraform code between different environments?

Terraform’s builtin way of doing this is called workspaces (which is, confusingly, different from the Terraform Cloud concept of “workspaces”). If you do go this route, my strong suggestion would be to avoid using the “default” workspace at all, and use a named (non-default) workspace for each environment.

There are some quirks / caveats to this approach; you may also want to look at or consider tools like terragrunt or terramate which can more easily allow a DRY terraform configuration and help to orchestrate different cloud environments, as well as add some additional tooling around managing multiple states.

Hi @wyardley,

Thank you very much for your reply. I do know how to use terraform.workspaces for different environments but I’m trying to prevent this because If I apply the configuration to wrong environment and don’t have versioning for the remote backend s3 bucket is very bad.

What I’m looking for is to use “locals” block in single file and use it for all terraform sub-modules. For example lets say I have in dev multiple *.tf files and want to apply locals for these files:

locals {

  dev = {
      resource-1 = "ec2-instance_ami" 
      resource-2 = "something_else"
      resource-3 = "something_else"
  }
}

Then in all *.tf files for the specific environments to use these locals as below:

resource "aws_instance" "example" {
  # ...

  tags = local.resource-1
}

Hrm, I think I see; what would be the benefit of using locals vs. tfvars at that point, though?