Using for_each and lookup in a data block does not return a string

I am attempting to use a for_each loop inside a data block to retrieve a value from a map(object(string)). I receive an error message below about the input not being a string. Is this due to a string of lists being made in the data block output when using for_each ?

My goal is to take each individual returned value from the data block and pass it over to a child module as a list of strings that are joined together.

data.tf

data "okta_group" "custom_okta_groups" {
    for_each = var.okta_users_defined

    name = lookup(each.value, "group_memberships", {})
}

terraform.tfvars

okta_users_defined = {
      map_key1 = {
             group_memberships = ["group"]
      }
}

Error message

Error: Incorrect attribute value type
  on ../../modules/okta_user/data.tf line 12, in data "okta_group" "custom_okta_groups":
  12:     name = lookup(each.value, "group_memberships", {})
    |----------------
    | each.value is object with 13 attributes
Inappropriate value for attribute "name": string required.

Child resource that is using data block attributes

resource "okta_user" "okta_users" {
  for_each = var.okta_users_defined

  // REQUIRED INPUTS

  first_name        = lookup(each.value, "first_name", "")
  last_name         = lookup(each.value, "last_name", "")
  login             = lookup(each.value, "login", "")
  email             = lookup(each.value, "email", "")
  second_email      = lookup(each.value, "secondary_email", "")
  group_memberships = [data.okta_group.custom_okta_groups[*].id]

I’m not familiar with the Okta provider, so this response is based on some guesses.

The okta_group data source takes a string value for name, but you are passing it a list(string). (As an aside, the default value for lookup should not be {} here, as that is neither a valid string or list value.)

Later you are binding all the group IDs to the group_memberships value, instead of doing so by username. Instead I imagine you want to look up the group IDs by name for this specific user.

Here’s an untested sketch of what that might look like:

locals {
  // Collect all groups which our users are members of
  group_names = toset(flatten(
      [for k, v in var.okta_users_defined: v.group_memberships]
    )
  )
}

// Look up group information by name for all groups
data "okta_group" "groups" {
    for_each = local.group_names

    name = each.value
}

resource "okta_user" "okta_users" {
  for_each = var.okta_users_defined

  first_name        = lookup(each.value, "first_name", "")
  last_name         = lookup(each.value, "last_name", "")

  // Map all of this user's groups by name to id
  group_memberships = [for g in lookup(each.value.group_memberships, []): data.okta_group.groups[g].id]
}

Hope this helps!