Answered: How should I do this nested loop?

Currently I have a variable with this structure (with hundreds of user/key pairs):

      "sftp_transfer_users": [
        {
          "user_name": "someperson",
          "public_key": "ssh-rsa foo"
        },
        {
          "user_name": "otherperson",
          "public_key": "ssh-rsa baz"
        }
      ]

And I can loop over that variable and create all the user keys like this:

resource "aws_transfer_ssh_key" "sftp_transfer" {
  for_each  = { for user in var.sftp_transfer_users : user.user_name => user }
  user_name = aws_transfer_user.sftp_transfer[each.value.user_name].user_name
  body      = each.value.public_key
  ...
}

We now have a need to support multiple keys per user, like this:

      "sftp_transfer_users": [
        {
          "user_name": "someperson",
          "public_keys": [
            "ssh-rsa foo",
            "ssh-rsa bar"
          ]
        },
        {
          "user_name": "otherperson",
          "public_keys": [
            "ssh-rsa baz"
          ]
        }
      ],

How should I redo my for_each loop to loop over that new data structure?

This ended up being what I wanted:

locals {
  user_keys = distinct(flatten([
    for user in var.sftp_transfer_users : [
      for key in user.public_keys : {
        user_name = user.user_name
        body      = key
        index     = index(user.public_keys, key)
      }
    ]
  ]))
}

resource "aws_transfer_ssh_key" "sftp_transfer" {
  for_each  = { for user in local.user_keys : "${user.user_name}.${user.index}" => user }
  user_name = aws_transfer_user.sftp_transfer[each.value.user_name].user_name
  body      = each.value.body
  ...
}

Thanks to this blog post for the inspiration: How to do a Terraform Nested for loop for Resources | by Adrian Causby | Geek Culture | Medium