My goal is to have this output:
DB_PASSWORD="secret1"
REDIS_PASSWORD="secret1"
But I can't make it work and I'm getting this error during terraform plan
.
Error: Invalid index
...
random_password.app_secrets is object with 2 attributes
The given key does not identify an element in this collection value.
Could you please help me how to fix this issue? Here's how my code looks like.
locals {
require_new_secrets = toset([
"db",
"redis"
])
}
resource "random_password" "app_secrets" {
for_each = local.require_new_secrets
length = 16
special = false
}
resource "aws_secretsmanager_secret" "app_secrets" {
name_prefix = "app-secrets-"
recovery_window_in_days = 7
tags = var.tags
}
resource "aws_secretsmanager_secret_version" "app_secrets" {
secret_id = aws_secretsmanager_secret.app_secrets.id
secret_string = <<-EOF
%{for x in local.require_new_secrets}
${upper("{x}_PASSWORD")}=${random_password.app_secrets["{x}"].result}
%{endfor}
EOF
}
Thanks in advance!
CodePudding user response:
As mentioned in my comment, the interpolation syntax in Terraform requires you to add a $
in front of any variable where substitution is required. For your code to work it is enough to add a $
in front of both {x}
placeholders:
resource "aws_secretsmanager_secret_version" "app_secrets" {
secret_id = aws_secretsmanager_secret.app_secrets.id
secret_string = <<-EOF
%{for x in local.require_new_secrets}
${upper("${x}_PASSWORD")}=${random_password.app_secrets["${x}"].result}
%{endfor}
EOF
}
More on interpolation syntax can be found in [1] and the example looks very similar to what you are trying to do.
[1] https://www.terraform.io/language/expressions/strings#directives