foreachterraformhcl

Create proper resource names using terraform for_each


I would like to create several service account using for_each loop with the names:

yandex_iam_service_account.loki["loki1"]
yandex_iam_service_account.loki["loki2"]
etc...

It is important to have these names because I am describing already existing service accounts.

Here is my main.tf

resource "yandex_iam_service_account" "loki" {
  for_each   = var.loki_accounts
  name       = each.key
  description = each.value.description
}

Here is my vars.tf

variable "loki_accounts" {
  description = "Map of Loki accounts to be created"
  type = map(object({
    description = string
    bucket_name = string
    secret_name = string
  }))
  default = {
    "loki2" = {
      description = "loki 1",
      bucket_name = "loki1",
      secret_name = "secret-path-1"
    },
    "loki2" = {
      description = "loki 2",
      bucket_name = "loki2",
      secret_name = "secret-path-2"

But terraform plan creates service accounts with names:

yandex_iam_service_account.loki["loki1"]
yandex_iam_service_account.loki["loki2"]
etc...

but not:

yandex_iam_service_account.loki1
yandex_iam_service_account.loki2

Could you please advice how to fix it? Thanks in advance!


Solution

  • Resource names can't be dynamic. Terraform requires literal resource names - you cannot use variables, string interpolation in resource names, etc.

    Hashicorp best practices for Terraform says:

    For consistency and readability, use a descriptive noun and separate words with underscores. Do not include the resource type in the resource identifier since the resource address already includes it.

    But if you are describing already existing service accounts it could be more suitable to use import block or command - https://developer.hashicorp.com/terraform/cli/import

    Then you can import these service accounts to resources created via for_each.