Search code examples
terraformterraform-aws-modules

Create aws_transfer_ssh_key from a map of user to SSH keys


I'm trying to create a transfer key from a map users to SSH keys

content_users = {
  "master" = [
    "ssh-rsa ...",
    "ssh-rsa ...",
    "ssh-rsa ...",
  ]
  "test" = [
    "ssh-rsa ...",
    "ssh-rsa ...",
  ]
}

The aws_transfer_user part is easy enough

resource "aws_transfer_user" "content" {
  for_each  = var.content_users
  server_id = aws_transfer_server.content.id
  user_name = each.key
  role      = aws_iam_role.transfer.arn
}

But I am trying to figure out how to do the aws_transfer_key which only accepts one ssh key

resource "aws_transfer_ssh_key" "content" {
  for_each = var.content_users
 server_id = aws_transfer_server.content.id
  user_name = each.key
  body      = "... SSH key ..."
}

I am thinking it is something I just have to follow with https://www.terraform.io/docs/configuration/functions/flatten.html#flattening-nested-structures-for-for_each


Solution

  • resource "aws_transfer_ssh_key" "content" {
      for_each = toset(flatten([
        for user, keys in var.content_users : [
          for key in keys : "${user}:@:${key}"
        ]
      ]))
      server_id = aws_transfer_server.content.id
      user_name = split(":@:", each.value)[0]
      body      = split(":@:", each.value)[1]
    }