I am new to Terraform and I’d like to generate key-value secrets from an input file users.yml. For every group I want to create a secret and for each user of the group I want to add a key value, where key is the user and value is a generated random password.
I would like to create dinamically a map like this:
grp_usr2 = tomap({"grp1" = {"users" = ["user1","user2","user3"], "psw" = ["psw1","psw2","psw3"]}, "grp2" = {"users" = ["user1","user4"], "psw" = ["psw4","psw5"]}})
The user name may be the same in different group but passwords must be different.
I am not able to associate a random password for each user in list of different group. I past my code.
users.yml
groups:
- name: "grp1"
path: "/grp1"
description: "grp1 group"
users: ["user1", "user2", "user3"]
- name: "grp2"
path: "/grp2"
description: "grp2 group"
users: ["user1, user4"]
locals.tf
locals {
group_details = try(yamldecode(file(var.secrets_file)).groups, [])
groups = merge(flatten([
for group in local.group_details : [{
"${group.name}" = {
name = group.name
path = group.path
description = try(group.description, null)
secret_string = try(group.secret_string, null)
users = group.users
}} ]
]
)...)
grp_usr2 = tomap({"grp1" = {"users" = ["user1","user2","user3"], "psw" = ["psw1","psw2","psw3"]}, "grp2" = {"users" = ["user1","user4"], "psw" = ["psw4","psw5"]}})
}
secrets.tf
resource "aws_secretsmanager_secret" "sm" {
for_each = local.groups
name = lookup(each.value, "path")
description = lookup(each.value, "description", null)
tags = var.tags
recovery_window_in_days = var.recovery_window_in_days
}
resource "aws_secretsmanager_secret_version" "sm-sv" {
for_each = local.groups
secret_id = lookup(each.value, "path")
secret_string = try(jsonencode(zipmap(lookup(lookup(local.grp_usr2, each.key),"users"), lookup(lookup(local.grp_usr2, each.key),"psw"))), null)
depends_on = [aws_secretsmanager_secret.sm]
lifecycle {
ignore_changes = [
secret_string
]
}
}
Thank you
CodePudding user response:
You can use random_password for that:
resource "random_password" "password" {
for_each = toset(local.flat_groups)
length = 16
special = true
override_special = "!#$%&*()-_= []{}<>:?"
}
locals {
group_details = try(yamldecode(file("users.yml")).groups, [])
flat_groups = flatten([
for group in local.group_details: [
for user in group.users:
"${group.name}-${user}"
]])
grup_urs2 = {for group in local.group_details:
group.name => {
users = group.users
psw = [for user in group.users: random_password.password["${group.name}-${user}"].result]
}
}