Terraform, can a resource be passed as a variable into a module?
This isn't currently possible - according to the Terraform Creating Modules page, a module's input variables can only be standard variable types: string
, list
, and map
.
I've encountered this same use case and have had to provide large lists of inputs to modules, which isn't ideal but seems to be the current state of the world.
This is possible with terraform > 0.12. You can use the object
type, butt you have to explicitly list fields that you use within your module.
# module's variables.tf
variable "parent_vnet" {
# List each field in `azurerm_route_table` that your module will access
type = object({
name = string
location = string
resource_group_name = string
})
}
# caller
resource "azurerm_route_table" "my_parent_vnet" {
# ...
}
module "my-module" {
parent_vnet = azurerm_route_table.my_parent_vnet
}
If you want to avoid passing long lists of attributes of other resources you can use the data
resources to avoid that.
Say you need all resources "provider" attributes within a module "consumer", pass in an identifier of the data source and then fetch all attributes using the data source within the module.
resource "producer" {
id = "id"
}
module "consumer" {
second-module-id = resource.producer.id
}
Within the "consuming" module you can now call access all attributes of the "producer" using the data source (provided your cloud provider has a data source):
data "producer-data" {
id = second-module-id
}
resource "resource" {
prop1 = data.prop1
prop2 = data.prop2
...
}