Home > front end >  How to create many secrets in AWS secrets manager using terraform
How to create many secrets in AWS secrets manager using terraform

Time:12-22

What I want to do is feed a list of key names to a module that will be used to generate many secrets with different random passwords in secrets manager.

I have tried many different things but have failed so far.

This is what I have currently:

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"

  ]
}

The Error:

│ 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...

CodePudding user response:

Unfortunately what you are providing is not even valid Terraform code. What I believe you would want to achieve the following:

// 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
      }
  }
}

You may want to check out the splat expressions for being able to iterate over multiple resources. This is used for the for expression in the secrets-manager-1 module.

  • Related