Search code examples
terraform

Get type of a variable in Terraform


Is there a way to detect the type of a variable in Terraform? Say, I have a module input variable of type any, can I do some kind of switch, depending on the type?

variable "details" {
  type = any
}

local {
  name = var.details.type == map ? var.details["name"] : var.details
}

What I want to archive is, to be able to pass either a string as shorthand or a complex object with additional keys.

module "foo" {
  details = "my-name"
}

or

module "foo" {
  details = {
    name = "my-name"
    age = "40"
  }
}

I know this example doesn't make much sense and you would like to suggest to instead use two input vars with defaults. This example is just reduced to the minimal (non)working example. The end goal is to have a list of IAM policy statements, so it is going to be a list of lists of objects.


Solution

  • terraform v1.0+ introduces a new function type() for this purpose. See https://www.terraform.io/language/functions/type