I have a module that has some resources such as es, kafka, rds, and so on.
This module needs inputs in the form below.
rds = {
enabled = 1
instance_class = “…”
…
}
The enabled flag sets the count option in the resource inside the module. However, when I set enabled as 0, I don’t want to specify any of the input variables such as instance_class, … and so on.
Is there any way ?
Hi @piljaechae,
In cases like this where there are some settings you only need to set one some particular component is “enabled”, it’s common to use the null
-ness of the definition of those settings as representing whether it’s enabled, rather than having a separate flag.
In your case I think you’re saying that you have an input variable defined something like this:
variable "rds" {
type = object({
enabled = number
instance_class = string
# ...
})
}
Instead, you could change that definition to make this variable optional and default to null
, and remove the explicit enabled
attribute:
variable "rds" {
type = object({
instance_class = string
# ...
})
default = null
}
This means that if the caller of your module leaves rds
unset, var.rds
will evaluate to null
elsewhere in the module. You can then use that characteristic to decide whether to enable the resources. If you’re doing that enabling using count
then you could write that like the following:
resource "aws_rds_cluster_instance" "example" {
count = length(var.rds[*])
instance_class = var.rds[count.index].instance_class
# ...
}
The above is a bit subtle, so I’ll explain it in parts:
-
var.rds[*]
uses the “splat” operator as a concise way to get either a single-element list or a zero-element list, depending on whether var.rds
is null
.
- We take the
length(...)
of that result, so that count = 0
when var.rds
is null and count = 1
otherwise.
- We then access attributes of
var.rds[count.index]
to get the “current element”, which allows Terraform to see that this expression is relevant only when count > 0
. (Otherwise the validator can complain that element zero doesn’t exist in cases where count = 0
.)
With this design, the caller of your module would just omit the rds
argument altogether in order to disable the RDS features, but if they do specify that variable then they’ll need to set all of the required attributes of that object.