Terraform: how to read list of maps?

扶醉桌前 提交于 2020-06-11 04:08:30

问题


See the example below:

data "aws_kms_secrets" "api_key" {
  count = "${length(keys(var.keys))}"

  secret {
    name    = "secret_name"
    payload = "${element(values(var.keys), count.index)}"
  }
}

resource "aws_api_gateway_api_key" "access_key" {
  count = "${length(keys(var.keys))}"

  name  = "${var.environment}-${element(keys(var.keys), count.index)}"
  value = "${lookup(element(data.aws_kms_secrets.api_key.*.plaintext, count.index), "secret_name")}"
}

It appears to be impossible to look up the plaintext values from the data resource.

value = "${lookup(element(data.aws_kms_secrets.api_key.*.plaintext, count.index), "secret_name")}"

Results in lookup: argument 1 should be type map, got type string in:

I have tried many combinations of element,lookup,*, and dictionary syntax nothing works.

my var.keys looks like:

keys = {
  key-name-one = "sssss"
  key-name-two = "sss"
}

回答1:


The trick here is to use the dictionary syntax to replace the element call, it behaves better with lists of maps.

value = "${lookup(data.aws_kms_secrets.api_key.*.plaintext[count.index], "secret_name")}"

its tempting to do data.aws_kms_secrets.api_key[count.index].plaintext that isn't valid HCL




回答2:


You can also access multiple secrets without using count and instead just adding multiple secret blocks like this:

data "aws_kms_secrets" "example" {
  secret {
    # ... potentially other configration ...
    name    = "master_password"
    payload = "AQEC..."
  }

  secret {
    # ... potentially other configration ...
    name    = "master_username"
    payload = "AQEC..."
  }
}

resource "aws_rds_cluster" "example" {
  # ... other configuration ...
  master_password = "${data.aws_kms_secrets.example.plaintext["master_password"]}"
  master_username = "${data.aws_kms_secrets.example.plaintext["master_username"]}"
}

This example is given in the AWS Provider version 2 upgrade guide as the aws_kms_secret data source is incompatible with Terraform 0.12 and so is replaced by the aws_kms_secrets (note the pluralisation) data source instead.

I've updated the docs for the aws_kms_secrets data source example to match this as well.

In Terraform 0.12 those secrets blocks will also be able to be dynamic as well so you should be able to do something like this:

data "aws_kms_secrets" "example" {
  dynamic "secret" {
    for_each = var.keys

    content {
      name    = secret.name
      payload = secret.payload
    }
  }
}

resource "aws_api_gateway_api_key" "access_key" {
  count = "${length(var.keys)}"

  name  = "${var.environment}-${element(keys(var.keys), count.index)}"
  value = "${lookup(data.aws_kms_secrets.api_key.plaintext), element(keys(var.keys), count.index)}"
}


来源:https://stackoverflow.com/questions/51543968/terraform-how-to-read-list-of-maps

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!