mhvelplund
mhvelplund

Reputation: 2351

Transform a list to a map with Terraform 0.11

Using Terraform 0.11.x (I don't care about 0.12), let's say I have a list keys and I want to transform it into a map, using something like:

locals {
  account = "287985351234"
  names   = ["alpha", "beta", "gamma"]
  region  = "eu-west-1"
}

data "null_data_source" "kms" {
  count = "${length(local.names)}"

  inputs = {
    key   = "${upper(local.names[count.index])}"
    value = "${format("arn:aws:kms:%s:%s:key/%s",local.region, local.account, local.names[count.index])}"
  }
}

output "debug" {
  value = "${data.null_data_source.kms.*.outputs}"
}

The output is a list of maps:

data.null_data_source.kms[2]: Refreshing state...
data.null_data_source.kms[0]: Refreshing state...
data.null_data_source.kms[1]: Refreshing state...

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

debug = [
    {
        key = ALPHA,
        value = arn:aws:kms:eu-west-1:287985351234:key/alpha
    },
    {
        key = BETA,
        value = arn:aws:kms:eu-west-1:287985351234:key/beta
    },
    {
        key = GAMMA,
        value = arn:aws:kms:eu-west-1:287985351234:key/gamma
    }
]

Is there any way to make it one map with all the keys like this?:

{
    ALPHA = "arn:aws:kms:eu-west-1:287985351234:key/alpha",
    BETA = "arn:aws:kms:eu-west-1:287985351234:key/beta",
    GAMMA = "arn:aws:kms:eu-west-1:287985351234:key/gamma"
}

Upvotes: 1

Views: 441

Answers (1)

mhvelplund
mhvelplund

Reputation: 2351

A guy called Loren on the SweetOps Slack channel gave me the solution. I'm leaving it here for anyone who comes by later:

locals {
  its_a_map = "${zipmap(data.null_data_source.kms.*.outputs.key, data.null_data_source.kms.*.outputs.value)}"
}

Upvotes: 2

Related Questions