Home > Blockchain >  How to create a list of data sources in Terraform?
How to create a list of data sources in Terraform?

Time:05-31

I have some secrets on AWS Secrets Manager. I already created a list of all the secrets' ARN, which looks like this

secretList  = {
      "secret1"  = "ARN1",
      "secret2"  = "ARN2"
}

I can retrieve the content of one single secret using Data source, for example

//Get the secret ID
data "aws_secretsmanager_secret" "secrets" {
    arn = "ARN1"
}
//Retrive the latest content
data "aws_secretsmanager_secret_version" "current" {
  secret_id = data.aws_secretsmanager_secret.secrets.id
}

Now I want to create a list of all my secrets' content, how can I do that? Since every secret can have multiple pairs of key/value, I'm thinking the results should look like this:

secretValue  = {
      "secret1"  = {"key1" = "value1","key2" = "value2"},
      "secret2"  = {"key1" = "value1","key2" = "value2","key3" = "value3"}
}

CodePudding user response:

You can use for_each:

data "aws_secretsmanager_secret" "secrets" {
    for_each = var.secretList
    arn      = each.value
}

data "aws_secretsmanager_secret_version" "current" {
  for_each  = var.secretList
  secret_id = data.aws_secretsmanager_secret.secrets[each.key].id
}

Then you can access the secrets using, for example:

data.aws_secretsmanager_secret_version.current["secret1"].secret_string
  • Related