Hi Team ,
Can I create a function in terraform and pass local arguments to it. Something like below !
error_count_chart_normal(chartName, (Optional)width, (Optional)height) {
type = “billbord”
chart_name = lookup(chartName, “Error (Count)”)
width = lookup(width, 2)
}
Hi @jithinbabu657,
Terraform does not have user-defined functions, but with some admittedly-heavier syntax you can often achieve a similar result by writing a module that contains only variables and output values, without declaring any resources.
It seems like your example is just applying some default values and not really doing any special computation, so if you’re not doing this in many places then I would suggest just writing out the expression directly and not trying to factor it out, but if you do want to turn this into a reusable module then this particular case would be quite a straightforward one because Terraform module input variables already have a sense of default values and so Terraform can deal with that automatically for you:
variable "chart_name" {
type = string
}
variable "width" {
type = number
default = 2
}
variable "height" {
type = number
default = 1
}
output "chart_def" {
value = {
type = "billbord"
chart_name = var.chart_name
width = var.width
height = var.height
}
}
To use this module you can call it with a set of arguments using the normal module
block syntax:
module "example" {
source = "./modules/chart-object"
chart_name = "Hello World"
}
Then elsewhere in the module you can refer to module.example.chart_def
to get the “return value” of the module, represented by an output value called chart_def
.
You can write multiple module
blocks with the same source
, creating the effect of multiple calls to this “function”, if you need to use this in multiple places with different arguments.
1 Like