Terraform module as "custom function"

Viewed 1364

It is possible to use some i.e. local module to return let' say same calculated output. But how can you pass some parameters? So each time you will ask for the output value you will get different value according to the parameter(ie different prefix)

Is it possible to pass resource to module and enhance it with tags?

I can imagine that both cases are more likely to be case for providers, but for some simple case it should work maybe. The best would be if they implemented some custom function that you will be able to call at will.

1 Answers

It is possible in principle to write a Terraform module that only contains "named values", which is the broad term for the three module features Input Variables (analogous to function arguments), Local Values (analogous to local declarations inside your function), and Output Values (analogous to return values).

Such a module would not contain any resource or data blocks at all and would therefore be a "computation-only" module, which therefore has all of the same capabilities as a function in a functional programming language.

variable "a" {
  type = number
}

variable "b" {
  type = number
}

locals {
  sum = var.a + var.b
}

output "sum" {
  value = local.sum
}

The above example is contrived just to show the principle. A "function" this simple doesn't really need the local value local.sum, because its expression could just be written inline in the value of output "sum", but I wanted to show examples of all three of the relevant constructs here.

You would "call the function" by declaring a module call referring to the directory containing the file with the above source code in it:

module "example" {
  source = "./modules/sum"

  a = 1
  b = 2
}

output "result" {
  value = module.example.sum
}

I included the output "result" block here to show how you can refer to the result of the "function" elsewhere in your module, as module.example.sum.

Of course, this syntax is much more "chunky" than a typical function call, so in practice Terraform module authors will use this approach only when the factored out logic is significant enough to justify it. Verbosity aside though, you can include as many module blocks referring to that same module as you like if you need to call the "function" with different sets of arguments. Each call to the module can take a different set of input variable values and therefore produce a different result.

Related