Using for_each in dynamic blocks for on/off switching

100 views
Skip to first unread message

Stuart Clark

unread,
May 22, 2019, 8:21:37 PM5/22/19
to terrafo...@googlegroups.com
I've just been upgrading my Terraform code to 0.12 and there's a pattern
I've started using which I'd like to hear people's opinions of.

Basically I'm using dynamic blocks in a few places to add/remove
sections based on a variable. The equivalent of using "count =
var.variable ? 1 : 0" for resources. It allows me to collapse a load of
duplicate resources I previously had (resource with X and resource
without X becomes a single resource with a dynamic block).

I'm doing this like so:

variable "environment" {
  type    = map(string)
  default = {}
}

locals {
  environment = length(var.environment) > 0 ? [""] : []
}

resource "aws_lambda_function" "lambda" {
  dynamic "environment" {
    for_each = local.environment
    content {
      variables = var.environment
    }
  }

  ...
}

It feels a little weird having a for_each where I'm not using the value
of the list at all (other than expecting it to have either exactly 0 or
exactly 1 element).

What do people think? Is there a better/neater/cleaner way of doing this?

--
Stuart Clark

Reply all
Reply to author
Forward
0 new messages