2

What's The Goal?

To take the following solution (that generates a secrets manager secret with a random password) and move from a Plaintext secret to a Key/Value secret.

Plaintext Secretsmanager Secret Solution

resource "random_password" "default_password" {
  length           = 20
  special          = false
}

# NOTE: Since we aren't specifying a KMS key this will default to using
# `aws/secretsmanager`/
resource "aws_secretsmanager_secret" "user_default" {
  name        = "user/default"
  tags        = local.tags
}

resource "aws_secretsmanager_secret_version" "secret_val" {
  secret_id     = aws_secretsmanager_secret.user_default.id
  secret_string = random_password.default_password.result
}

This is a functional solution that produces a plaintext secret with a randomly generated password enter image description here

Attempted Solution

This is the first solution I tried based on the terraform docs for secretsmanager_secret_version which unfortunately doesn’t work for randomly generated Passwords

  // TODO: Generalize this to produce a password once per (username, company)
  //       tuple in a list.
  resource "random_password" "default_password" {
    length           = 20
    special          = false
  }

  # NOTE: Since we aren't specifying a KMS key this will default to using
  # `aws/secretsmanager`/
  resource "aws_secretsmanager_secret" "user_default" {
    name        = "user/default"
    tags        = local.tags
  }

  variable "secret_contents" {
    default = {
>>    password = random_password.default_password.result
      company = "test"
    }

    type = map(string)
  }

  resource "aws_secretsmanager_secret_version" "secret_val" {
    secret_id     = aws_secretsmanager_secret.user_default.id
    secret_string = jsonencode(var.secret_contents)
  }

this hits a Variables may not be used here. error.

AlexLordThorsen
  • 8,057
  • 5
  • 48
  • 103
  • 1
    `secret_contents` needs to be a `local` and not a declared `variable` since the default value is based on values generated during application. – Matthew Schuchard Sep 02 '21 at 12:30

1 Answers1

5
  resource "random_password" "default_password" {
    length           = 20
    special          = false
  }

  # NOTE: Since we aren't specifying a KMS key this will default to using
  # `aws/secretsmanager`/
  resource "aws_secretsmanager_secret" "user_default" {
    name        = "user/default"
    tags        = local.tags
  }

  resource "aws_secretsmanager_secret_version" "secret_val" {
    secret_id     = aws_secretsmanager_secret.user_default.id
    # TODO: Figure out a way to generate mapping structure that presents this
    #       key/value pair structure in a more readable way. Maybe use template files?
    secret_string = jsonencode({"password": "${random_password.default_password.result}"})
  }

Will produce a key/value secret with a randomly generated password

enter image description here

AlexLordThorsen
  • 8,057
  • 5
  • 48
  • 103