Tfvars assigned variable value to be used for calling the root module variable

Hi,
I am trying to call a terraform root module variable from *.auto.tfvars file while calling the child module like below,

Root module variables:

variable "new_map" {
type  = map(any)
default = {}
}

variable "ssh_key_name1" {
type  = map(any)
default = {}
}

variable.auto.tfvars file,

new_map = {
<other_values_are defined here as part of map variable>
ssh_key_name = "my-ssh-key"
}

Trying to use *tfvar ssh_key_name value into Root module call like below but not working,

module "my-module"{
   source = "./modules/ec2"
  for_each = var.new_map != null ? var.new_map : {}
   **ssh_key_name = var.${each.value.ssh_key_name}**
}

If not directly via the above approach is there anyother way i can achieve this. Because my only source is *.auto.tfvars which has the ssh_key_name and it can change based on your setting. So i need to pass the value to root module and call it like var.<ssh_key_name> . appreciate your help on this.

Hi @ulags.n,

The correct syntax for accessing an element of a map is as follows:

  ssh_key_name = var.ssh_key_name[each.value]

With a configuration like this, you’ll need to make sure that the values in var.new_map all correlate with keys in var.ssh_key_name, or else you will see map element lookup errors.


Incidentally, you can avoid the need to test whether your maps are null by declaring them as non-nullable:

variable "new_map" {
  type     = map(string)
  default  = {}
  nullable = false
}

variable "ssh_key_name" {
  type     = map(string)
  default  = {}
  nullable = false
}

If you set nullable = false then Terraform will ensure that var.new_map will never be null. In any situation where it might’ve been null, Terraform will use the default value (an empty map) instead.

Hi @apparentlymart ,
Thank you for the response. What if i wanted to call a different string variable like ssh_key_name from the root module. Assume i am getting the name of the variable from *tfvars as a string. Now i need to convert that into a variable call is that possible ?

No, you can only dynamically choose elements from a map. You cannot dynamically choose which variable to take the map from.

However, anything you can achieve with multiple variables should be achievable with a single variable of a mapping type: the dynamic part just becomes the keys of that map rather than the variable name.