TerraformConditionalModule

nicolaw 4th December 2020 at 8:40pm
Terraform

Example Code

$ cat main.tf
variable "enable_foo" {
  type    = bool
  default = false
}

module "foo" {
  for_each = toset(var.enable_foo ? ["enabled"] : [])
  source   = "./foo_module"
  name     = "myfoo"
}

output "bacon" {
  value = var.enable_foo ? module.foo["enabled"].bacon : ""
}

output "foo" {
  value = var.enable_foo ? module.foo["enabled"] : {}
}

$ cat foo_module/main.tf
variable "name" {}

output "name" {
  value = var.name
}

output "bacon" {
  value = "cheese"
}

Results

$ terraform init >/dev/null; terraform apply -auto-approve -var enable_foo=true

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

bacon = "cheese"
foo = tomap({
  "bacon" = "cheese"
  "name" = "myfoo"
})

$ terraform init >/dev/null; terraform apply -auto-approve -var enable_foo=false

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

bacon = ""
foo = {}