How can I use terraform module output values to set variables

938 views Asked by At

I am really new to terraform so please forgive anything I say incorrectly. I come from a normal programming background.

In order to avoid duplication, I want to use a module output value to set a variable value in variables.tf using string interpolation. When I do this and then do 'terraform validate' I get an Error: Variables not allowed.

String interpolation worked fine when I used the output value in a different .tf file to set a resource parameter like this:

  bucket  = google_storage_bucket.b.name
  role    = "roles/storage.objectViewer"
  members = ["abc${module.my_module.project_number}xyz"]
}

My terraform structure is:

root/module/<module name=""> # this is the module source

The module is called "my_module" and has an output e.g.

output "project_number" {
  value = google_project.project.number
}

In root/variables.tf I have:

   type = string
   default = "abc${module.my_module.project_number}xyz"
}

but this does not work, it throws and error because I have use ${module.....} in the default value setting.

I also tried creating a local in variables.tf

  my_project = module.my_module.project_number
}

and then tried using that in the variable: default = "abc${local.my_project}xyz"

but that did not work either.

I have tried to find answers to this, of course, but have failed and may be completely missing a point, so I apologise in advance if I am being stupid :/

1

There are 1 answers

0
user686027 On

I have solved this. I had to use locals, as these have scope local to modules.

If I declare the whole list in a local it works ok.

I couldn't use variables as they are global and wherever the variable may be accessed could be outside of the root module which created the module with output values. Then the value may be used without being valid. I don't know why null checks don't mean this is possible, another thing to investigate sometime