Hi,
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 do add a key value, where key is the user and value is a 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 groups, using “random_password” resource.
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