Convert for_each datas to list/map


I’m using terraform 12 and i my problem is i guess a purely terraform syntaxt missunderstood from me.

I’m getting AWS KMS Key from a for_each loop in a data source object as bellow:

data "aws_kms_key" "kms_key" {
  for_each = toset( //partners is a list of string ["test","test2"]
  key_id = "alias/aws/s3" //just for the example, it really gets cutom KMS key here

Then, i try to create a S3 bucket for each value in the partner list with their specific KMS key associated:

resource "aws_s3_bucket" "bucket" {
  for_each = local.kms_key_binding
  bucket   = "bucket-${each.key}"
  server_side_encryption_configuration {
    rule {
      apply_server_side_encryption_by_default {
        kms_master_key_id = each.value.arn
        sse_algorithm     = "aws:kms"

You can see on the s3 bucket for_each loop that i use a local variable which looks like:

locals {
  kms_key_binding = zipmap(,data.aws_kms_key.kms_key)

Here is where i’m blocked. I tried lot of things but nothing works. What i need is to have a map with as key the value in the partners list (e.g test), and as key the ARN of the key which is in the data kms_key.

Can you help me pls ?

The error i get says that the data kms_key is not considered as a list but as object with attributs. How can i get a list from that to make a map with my desired key/value pairs ?

    | data.aws_kms_key.kms_key is object with 2 attributes
    | is list of string with 2 elements

Call to function "zipmap" failed: number of keys (2) does not match number of
values (1).

Thanks !

I fixed the problem by creating a local variable as follow:

kms_key_list = [
  for kms_key in data.aws_kms_key.kms_key : {
    arn = kms_key.arn

kms_key_binding = zipmap(,local.kms_key_list)

I worked on this yesterday during all afternoon, that’s why i asked the question this morning. Better have a rest after 4 hours looking for a solution… it comes quicker the next day !

Have fun,