-
Notifications
You must be signed in to change notification settings - Fork 9.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Feature: Conditionally load tfvars/tf file based on Workspace #15966
Comments
Hi @atkinchris! Thanks for this suggestion. We have plans to add per-workspace variables as a backend feature. This means that for the local backend it would look for variables at We were planning to prototype this some more before actually implementing it, since we want to make sure the user experience makes sense here. With the variables stored in the backend we'd probably add a local command to update them from the CLI so that it's not necessary to interact directly with the underlying data store. At this time we are not planning to support separate configuration files per workspace, since that raises some tricky questions about workflow and architecture. Instead, we plan to make the configuration language more expressive so that it can support more flexible dynamic behavior based on variables, which would then allow you to use the variables-per-workspace feature to activate or deactivate certain behaviors without coupling the configuration directly to specific workspaces. These items are currently in early planning stages and so no implementation work has yet been done and the details may shift along the way, but this is a direction we'd like to go to make it easier to use workspaces to model differences between environments and other similar use-cases. |
Awesome, look forward to seeing how workspaces evolve. We'll keep loading the workspace specific variables with |
@apparentlymart is there another github issue that is related to these plans? Something we could subscribe to? I'm interested in this because we currently have a directory in our repo with If these were kept in some backend-specific location, that would be great! |
We just want to reference a different VPC CIDR block based on my workspace. Is there any other workaround that could get us going today? |
A few common workarounds I've heard about are:
|
@apparentlymart thanks. I think option one is best. 3 doesn't work as we create the VPC with terraform in the same workspace. |
@apparentlymart what is the estimated timeline for this functionality, could it be stripped down to just the tfvars and not the dynamic behaviour based on variables? It sounds like you have a pretty solid understanding of how the tfvars being loaded for a particular workspace is going to work. |
Hi @james-lawrence, In general we can't comment on schedules and timelines because we work iteratively, and thus there simply isn't a defined schedule for when things get done beyond our current phase of work. However, we tend to prefer to split up the work by what subsystem it relates to in order to reduce context-switching, since non-trivial changes to Terraform Core tend to require lots of context. For example, in 0.11 the work was focused on the module and provider configuration subsystems because that allowed the team to reload all the context on how modules are loaded, how providers are inherited between modules, etc and thus produce a holistic design. The work I described above belongs to the "backends" subsystem, so my guess (though definitely subject to change along the way) is that we'd try to bundle this work up with other planned changes for backends, such as the ability to run certain operations on a remote system, ability to retrieve outputs without disclosing the whole state, etc. Unfortunately all I can say right now is that we're not planning to look at this right now, since our current focus is on the configuration language usability and work is already in progress in that area which we want to finish (or, at least, reach a good stopping point) before switching context to backends. |
That becomes quite hard to manage when you are dealing with multiple aws accounts and terraform workspaces |
Can anyone explain what the difference is between terraform.tfvars and variables.tf file, when to use one over the other? And do you need both or just one is good enough? |
[variables].tf has definitions and default values, .tfvars has overriding values if needed |
Yet another workaround (based on the @apparentlymart 's "first" workaround) that allows you to have workspace variables in different files (easier to diff). When you add new workspaces you only need to a) add the file b) add it to the list in the merge. This is horrible, but works. workspace1.tf
workspace2.tf
main.tf
|
Taking @matti's strategy a little further, I like having default values and only customize per workspace as needed. Here's an example: locals {
defaults = {
project_name = "project-default"
region_name = "region-default"
}
}
locals {
staging = {
staging = {
project_name = "project-staging"
}
}
}
locals {
production = {
production = {
region_name = "region-production"
}
}
}
locals {
workspaces = "${merge(local.staging, local.production)}"
workspace = "${merge(local.defaults, local.workspaces[terraform.workspace])}"
}
output "workspace" {
value = "${terraform.workspace}"
}
output "project_name" {
value = "${local.workspace["project_name"]}"
}
output "region_name" {
value = "${local.workspace["region_name"]}"
} When in workspace
When on workspace
|
I've been thinking about using Terraform in automation and doing something like |
can someone please give example/template of "Terraform to conditionally load a .tfvars or .tf file, based on the current workspace." Even old way is worked for me. I just wanted to run multiple infra from a single directory. |
@farman022 Just use the |
Like @mhfs strategy but with one merge:
|
|
is this feature added in |
No, this hasn't been added yet (current version is While we try to follow up with issues like this in Github, sometimes things get lost in the shuffle - you can always check the Changelog for updates. |
This is a resource that I have used a couple of times as a reference to setup a Makefile wrapping terraform, maybe some of you find it useful: |
I use it too. It is a good decision |
This is a great idea for most. Ironically this is the one solution that can't work for Terraform Enterprise customers because the terraform cli is invoked by the TFE node. Funny when you pay only for it to be worse 🤦 |
very clever, but it's possible to get it wrong if you forget to automatically get the tf workspace, but after going through the whole thread here, I'll roll with this, thanks! |
@infogulch What if you do
@rauerhans could you elaborate? |
It could be dangerous if you think you're on dev, run this command, but you're actually on the prod workspace so you apply to production. That's why I have Oh My Zsh and it always shows me which workspace I'm on before running any Terraform command. |
This is my second day of writing TF script for a multi-staging setup and I think I should switch to a different tool. For me it looks like that there is no clean solution available for using different tfvars files per workspace (with Terraform Cloud). The workarounds described here only apply to running/applying TF locally. Why isn't there any option in the TF Cloud UI where I can specify which tfvars files should be used? This seems so simple... |
@raman-nbg yes, do it before you have massive set of terraform written. I wish I was you. |
@raman-nbg in TFC we ended up using ( Something similar is documented here: https://support.hashicorp.com/hc/en-us/articles/4416764686611-Using-Terraform-Variable-Definition-Files-in-Terraform-Cloud-Enterprise |
Will this feature ever be added? It's been almost 5 years since this issue was opened |
I don't think so, haha |
still waiting... 😂 |
This issue is not currently prioritized. It does rank highly on our list of most requested issues, however that does not guarantee it will be addresses in the near future. Thanks for your interest and your patience. |
here is yet another workaround structure
Now all workspace specific values can be references as added bonus you get an error trying to run in a workspace that isn't defined in locals |
|
@oniGino Reasonable approach, though without a bit of juggling it has the disadvantage of coupling the settings for all possible environments into a single file. I tend to use this pattern quite a lot in various languages - it's essentially an poor-man's DI ;) |
@github-usr-name Although I do not work for Hashicorp, I can almost guarantee you that they know exactly what "prioritized" means; in this context, "not currently prioritized", as in, "we have not assigned this issue a priority in our backlog/work queue". |
Somehow inventing a whole new language (HCL v1) over the adoption of yaml/json or CUE /jsonet took "priority" over sensible features like this. I find it strange that golang-friendly devs would not want to create conventions around such a common feature; the language itself preaches idioism and "readability"... my sad $0.02 |
Not currently prioritized = this issue does not affect terraform cloud
… On 24. Aug 2022, at 22.56, github-usr-name ***@***.***> wrote:
This issue is not currently prioritized. It does rank highly on our list of most requested issues
^^^ I do not think you know what this word means. The issue is clearly a high priority for your customers.
—
Reply to this email directly, view it on GitHub, or unsubscribe.
You are receiving this because you were mentioned.
|
Your comment is off-topic for reason that this issue has nothing to do with configuration language, but with how deviations can be introduced. AFAIK HCL is used in multiple HashiCorp products and therefore on it's own it makes perfectly sense. But I'm in cohort who says, that a declarative language is a bad idea for infrastructure management or for every dynamic task. Of course, there are changes since terraform 0.12 which made terraform usable for most use cases. Back to you comment. Your suggestions would make it even worse. yaml/json/jsonnet are more dysfunctional than hcl. And cue was introduced at the end of 2018, long after hcl was used in production world wide. I never used cue (and don't plan to do that), but at first glance there is no real benefit for HashiCorp and(!) the community, but a bunch of disadvantages. Therefore, if switch to another language, then, probably, the best choice could be a general purpose language, like pulumi did it. |
It would be very nice if this was built into Terraform. NOTE: that AssumptionsassumptionsIf there are consistent workspace names such as # ue1-prod.tfvars
short_region = "ue1"
env = "prod" # ue1-dev.tfvars
short_region = "ue1"
env = "dev"
Option 1: consistent workspaces with a
|
can I +1 this feature request? I have a workspace 'production' and i was really surprised when I dropped a terraform.tfvars file into terraform.tfstate.d/production/ and it didn't automatically read from it. |
This doesn't solve the direct terraform integration part, but this script makes it easier to not schlep around https://gist.github.com/greyvugrin/d7e43b4834796101c6c328718a1b7250
|
I was able to do this with Terraform Cloud by adding an environment variable to the workspace: Now when I run It would be better if we could apply this in the code itself though. |
One hard reason to support conditionally loading tf files is that As for working with multiple workspaces, I have a tool that automatically sets |
Here's my hacky workaround for the issue in the meantime: Consider the directory structure:
In order to load either
Obviously this only works if the current working directory is not expecting these input variables but instead we load them as local variables that we can then pass as input variables to a module. It's not exactly what's being asked for but hopefully this might be good enough for some in the meantime. |
As of Terraform version 1.8 the provider specific function terraform {
required_providers {
terraform = {
source = "terraform.io/builtin/terraform"
}
}
}
locals {
# All workspace specific variables that are loaded based on the active workspace.
ws = provider::terraform::decode_tfvars(file("${terraform.workspace}.tfvars"))
}
module "example" {
# …
variable_a = local.ws.variable_a
# …
} It works great. Unfortunately, the big disadvantage is that this break auto-completion of most editors as well as "type safety" because the loaded variables can not be evaluated beforehand. It also required the explicit definition of the This is basically @TheShahin's setup, but simplified even more which also allows to use HCL instead of JSON. |
Feature Request
Terraform to conditionally load a
.tfvars
or.tf
file, based on the current workspace.Use Case
When working with infrastructure that has multiple environments (e.g. "staging", "production"), workspaces can be used to isolate the state for different environments. Often, different variables are needed per workspace. It would be useful if Terraform could conditionally include or load variable file, depending on the workspace.
For example:
Other Thoughts
Conditionally loading a file would be flexible, but possibly powerfully magic. Conditionally loading parts of a
.tf
/.tfvars
file based on workspace, or being able to specify different default values per workspace within a variable, could be more explicit.The text was updated successfully, but these errors were encountered: