Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define global variables in terraform?

Tags:

terraform

I have a terraform project I am working on. In it, I want a file to contain many variables. I want these variables to be accessible from any module of the project. I have looked in the docs and on a Udemy course but still don't see how to do this. How does one do this in terraform?

like image 267
Dan Avatar asked Sep 11 '25 23:09

Dan


2 Answers

I don't think this is possible. There are several discussions about this at Github, but this is not something the Hashicorp team wants.

In general we're against the particular solution of Global Variables, since it makes the input -> resources -> output flow of Modules less explicit, and explicitness is a core design goal.

I know, we have to repeat a lot of variables between different modules

like image 170
pabloxio Avatar answered Sep 13 '25 14:09

pabloxio


For pathing constants between lots of modules we can use the following simple way.

/modules/global_constants/outputs.tf:

Describe module with global constants as outputs:

output "parameter_1" {
  value     = "value_1"
  sensitive = true
}

output "parameter_2" {
  value     = "value_2"
  sensitive = true
}

/example_1.tf

After we can use in any *.tf

module "global_settings" {
   source = "./modules/global_constants"
}

data "azurerm_key_vault" "keyvault" {
   name                = module.global_settings.parameter_1
   resource_group_name = module.global_settings.parameter_2
}

/modules/module2/main.tf

Or in other any modules:

module "global_settings" {
   source = "../global_constants"
}

data "azurerm_key_vault" "keyvault" {
   name                = module.global_settings.parameter_1
   resource_group_name = module.global_settings.parameter_2
}
like image 34
Alex Malyshev Avatar answered Sep 13 '25 14:09

Alex Malyshev