如何使用 Terraform 在 AWS 机密管理器中创建多个机密

How to create many secrets in AWS secrets manager using terraform

我想要做的是将密钥名称列表提供给一个模块,该模块将用于在机密管理器中生成许多具有不同随机密码的机密。

我尝试过很多不同的东西,但到目前为止都失败了。

这是我目前拥有的:

module "secrets-manager-1" {

  source = "lgallard/secrets-manager/aws"

  for_each = var.list
  secrets = {
    "${each.value}" = {
      description             = each.value
      recovery_window_in_days = 7
      secret_string           = random_password.special_password.result
    }
  }

  tags = var.standard_tags
}

resource "random_password" "special_password" {
  count = 2
  length = 16
  special = true
}

variable "list" {
  type    = list(string)
  default = [
    "secret_key_1",
    "secret_key_2"

  ]
}

错误:

│ Error: Invalid for_each argument
│
│   on ..\..\modules\jitsi\jitsi_secrets.tf line 54, in module "secrets-manager-1":
│   54:   for_each = var.list
│     ├────────────────
│     │ var.list is list of string with 2 elements
│
│ The given "for_each" argument value is unsuitable: the "for_each" argument must be a map, or set of strings, and you have provided a value of type list of string.
╵
Releasing state lock. This may take a few moments...

很遗憾,您提供的甚至不是有效的 Terraform 代码。我相信您希望实现以下目标:

// Create N random password. In this case N = 2
resource "random_password" "special_password" {
  count   = 2
  length  = 16
  special = true
}

// Import a third party module
module "secrets-manager-1" {

  source = "lgallard/secrets-manager/aws"

  // Loop through the random_passowrd resouces and create the secrets
  secrets = {
      for index, pwd in random_password.special_password.*.result : "${element(var.list, index)}" => {
          secret_string: "${pwd}",
          recovery_window_in_days = 7
      }
  }
}

您可能想查看 splat expressions 以了解是否能够遍历多个资源。这用于 secrets-manager-1 模块中的 for 表达式。