Reusable values inside of for_each


In this feature request, it’s asked to being able to use locals inside of a resource. As far as I know, this still isn’t possible.

However, in this reply comment an alternative suggestion is provided. Is it possible to modify the example in this comment, to work with variables of the list(object) type?

So, is it possible to convert the below:

variable "objects" {

  type = list(object({

    Name       = string

    Identifier = string



resource "example" "example" {

  for_each = { for n in var.object : n.Name => n }


To incorporate the functionality of expressions, for transformations that I want to re-use multiple times?

Best regards

Hi @aleqsss,

I’m not totally sure I understand what you’re trying to do but from your example I think perhaps you’re asking how to combine the existing attributes in the objects in var.objects with some additional attributes only for use inside the resource "example" "example" block.

One way to get that done would be to use the merge function to merge the existing objects with new objects that have the additional attributes:

resource "example" "example" {
  for_each = {
    for o in var.object : => merge(o, {
      upper_identifier = upper(o.identifier)

  # ...

Hello @apparentlymart,

This does the job for me just fine, thank you for that, appreciated!

I wanted to be able to use functions on some object values while inside of the loop, so that I don’t have to repeat myself in the resource creation block, implementing the same logic over and over again, for example:

Instead of this:

resource "example" "example" {
  for_each = { for o in var.object : o.Name => o }

  virtual_machine_name      = "name-${replace(, "X", "Y")}${upper(each.value.identifier)}-vm"
  virtual_machinen_nic_name = "name-${replace(, "X", "Y")}${upper(each.value.identifier)}-nic$"

I now use this (as per your answer):

resource "example" "example" {
  for_each = { for o in var.object : o.Name => merge(o, {
      combined_name = "${replace(, "X", "Y")}${upper(each.value.identifier)}"

  virtual_machine_name      = "name-${each.value.combined_name}-vm"
  virtual_machinen_nic_name = "name-${each.value.combined_name}-nic$"

Is this somewhat equivalent to your example here? I want to achieve the same, but on a loop on a list(object) variable instead, so that I don’t have to repeat myself, just as that example suggests. And because of that exact example isn’t applicable on a loop on a list(object), I’m searching for the equivalent on such.

Your suggestion in your reply here works and does the job for me, is it in some way bad practice to use this in my case?