Hi,
I am fairly new to terraform and I could not find any tutorial using variable to bundle variables.
Let’s say I am using a provider with 12ish variables. And I wish to have a superset and to only use one variable to represent the 12ish variables.
For example, small, medium, large for VM size. Which will be translated to vcpu, ram, os, etc…
I’m not sure I’m fully understanding what you are intending so I’m going to describe what I understood first:
It sounds like you want to create an abstraction where a variety of settings will be reduced to a small set of “presets” that the caller of your module can choose just with a single keyword. The module would be responsible for defining what e.g. “small” and “medium” mean, and the caller would just specify the one keyword.
If I understood that correctly, the way I’d implement that is to declare an input variable to represent the keyword and then write a lookup table as a map in a local value to specify the values for the various physical settings your presets will represent.
variable "size_preset" {
type = string
validation {
condition = contains(["small", "medium", "large"], var.size_preset)
error_message = "Size preset must be either \"small\", \"medium\", or \"large\"."
}
}
locals {
size_presets = tomap({
small = {
cpu_cores = 1
ram_gb = 8
}
medium = {
cpu_cores = 2
ram_gb = 16
}
large = {
cpu_cores = 8
ram_gb = 32
}
})
selected_size = local.size_presets[var.size_preset]
}
With the above declarations, elsewhere in your module you can write expressions like local.selected_size.cpu_cores and local.selected_size.ram_gb to get the attributes that belong to the size preset the caller selected. I included a validation rule to help give the module user good feedback if they select an unsupported size preset.
Thank for undestanding my needs. Your answer solve my issue in a nice and clean way.
My implementation was dirtier compare to your. I had multiple variable and extensive usage of lookup. You did something similar but with fewer lines and it’s easier to add another preset.