Creating a nested JSON output

Hi,

I have seen some similar questions but I couldn’t work out how to construct “expected” access_keys output as shown below. To be fair the “current” output is not that appealing.

Thanks

Current

access_keys = {
  "developer-1" = "ID: AKIAFL1 => SECRET: wcBMA6Wd....mm5Ks3fg=",
  "developer-2" = "ID: FDGAFD1 => SECRET: ds54gfgF....dsdY45fd="
}

Expected

access_keys = {
  "developer-1" = {
      "id" = "AKIAFL1",
      "secret" = "wcBMA6Wd....mm5Ks3fg="
  },
  "developer-2" = {
      "id" = "FDGAFD1",
      "secret" = "ds54gfgF....dsdY45fd="
  }
}

Full code

locals {
  users = { for item in [
    {
      name : "developer-1",
      pgp_key : "mQENBGLyVtc....oc4oZqpBmjUPkzW"
    },
    {
      name : "developer-2",
      pgp_key : "fdsdNBGLkj....fea657hYh33dsf33"
    }
  ] : item.name => item }
}

resource "aws_iam_user" "user" {
  for_each = local.users

  name = each.value.name
}

resource "aws_iam_access_key" "user" {
  for_each = aws_iam_user.user

  user    = each.value.name
  pgp_key = local.users[each.key].pgp_key
}

output "access_keys" {
  value = {
    for name, user in aws_iam_access_key.user : name => "ID: ${user.id} => SECRET: ${user.encrypted_secret}"
  }
}

Hi @wevovib720,

The “Expected” access_keys you shared shows a map of objects where each object has id and secret attributes.

You can construct a value of that shape using the following expression:

output "access_keys" {
  value = tomap({
    for name, user in aws_iam_access_key.user : name => {
      id     = user.id
      secret = user.encrypted_secret
  })
}

The tomap(...) call here tells Terraform that the result of the for expression is a map of objects rather than an objects with nested objects inside it, which isn’t super important but helps to clarify how this result is intended to be used.

The more important thing is that the value portion of the for expression, after the => symbol, is an object constructor delimited by { ... }, and so it will construct an object value based on the attributes defined inside.

1 Like

It works as expected thank you!