Reputation: 9411
I have a set of resources that I want to create in Terraform, some created natively using resource
and some by calling module
. I need several sets like that. One set is looking like
module "my_secret_one" {
source = "rhythmictech/secretsmanager-random-secret/aws"
version = "1.2.0"
length = 16
name = "my_secret_one"
description = "..."
}
resource "postgresql_role" "my_secret_one_role" {
name = "my_secret_one"
login = true
password = module.my_secret_one.secret
}
// and few other resources also dependent on "my_secret_one".
Now, I actually have several secrets, my_secret_one, my_secret_two, my_secret_three...
How can I declare in terraform the creation of all modules and resources for all of these using for_each
?
Upvotes: 0
Views: 252
Reputation: 74064
Your first step here would be to define a collection which describes the objects you want to create. It looks like in your case it's only the name and description that will vary between the secrets, so perhaps this is a good candidate for the variable for defining those:
variable "secrets" {
type = map(object({
description = string
}))
}
(If you only intend to use this internally within your module then you could alternatively use a Local Value instead of an input variable, but the principle of making a map of objects remains the same either way.)
You can then use that map as the for_each
for your module, and the module as the for_each
for the Postgres role, so Terraform can see the relationships between these objects:
module "secret" {
source = "rhythmictech/secretsmanager-random-secret/aws"
version = "1.2.0"
for_each = var.secrets
name = each.key
description = each.value.description
length = 16
}
resource "postgresql_role" "secret" {
for_each = module.secret
login = true
password = each.value.secret # each.value here is an instance of module.secret
}
The usual caveats about using Terraform to manage secrets apply here: note that Terraform will need to track the secret value as part of state snapshots, and so you should make sure your state snapshots for this configuration are stored in a sufficiently-secured location. For more information, see State: Sensitive Data in the Terraform documentation.
Upvotes: 2