Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load a specific tfvars variables file in my Terraform Cloud workspace

Tags:

terraform

I wish to specify which .tfvars file to load on my workspaces.

Managing variables with files is much easier compared to entering everything in the workspaces. I'll explain.

I have two Worspaces:

  • database-qa
  • database-prod

Repo for the workspaces looks like this:

├── database/
│   ├── main.tf
│   ├── main.qa.tfvars
│   ├── main.prod.tfvars

I want to load main.qa.tfvars for the database-qa workspace, and main.prod.tfvars for the database-prod workspace, naturally.

I keep the secrets/passwords on the workspace variables for security, and use the tfvars for non-sensitive configurations such as names, versions, etc, for convenience. I find it much easier than adding all to the variables to the workspace in the cloud.

I checked the documentation but I can't find a way to do it.

There is the option to use *.auto.tfvars variable definitions for file names but it will end up loading qa and prod files and that won't work properly.

Is it possible to do it? What are the alternatives?

like image 579
Evandro Pomatti Avatar asked Oct 25 '25 00:10

Evandro Pomatti


2 Answers

One solution is to create generic Terraform code on root directory, and create one directory per environments.

├── database/
│   ├── main.tf
│   ├── qa/
│   |   ├── qa.auto.tfvars
│   |   ├── root.tf
│   ├── prod/
│   |   ├── prod.auto.tfvars
│   |   ├── root.tf

And in root.tf, just point to root directory as local module.

module "database" {
  source  = "../"
  cpu = var.cpu
}

[...]

On Terraform Cloud, for each workspace, in General Settings you have to override Terraform Working Directory, and configure directory qa or prod.

And that's it !

like image 61
Antoine Avatar answered Oct 27 '25 01:10

Antoine


After a lot of reading and help with this thread I found a solution/workaround.

First of all, Terraform Cloud does not support specifying the .tfvars file to be loaded in the workspace run, at this time. It is not clear if it is planned on the backlog or not.

Terraform CLI however supports it with the following command and it works fine if you create your pipeline, but risky to run it manually.

-var-file=<filename>.tfvars

Since I'm using Terraform Cloud I ended up with the following configuration. It'll have to be copied to all workspaces, but it works.

variable "TFC_WORKSPACE_NAME" {
  type = string
}

locals {
  env = merge(
    yamldecode(file("env/${var.TFC_WORKSPACE_NAME}.yaml"))
  )
}

resource "azurerm_resource_group" "group" {
  name     = local.env.group
  location = local.env.location
}
like image 33
Evandro Pomatti Avatar answered Oct 27 '25 01:10

Evandro Pomatti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!