0
votes

I'm trying to create GCP SQL DBs by iterating a list of string using Terraform's for_each and count parameter and the other loop is for the map keys (maindb & replicadb).

Unfortunately, I get the error that appears below.

Is it possible to do this is Terraform?

variables.tf

variable "sql_var" {
    default = {
        "maindb" = {
            "db_list" = ["firstdb", "secondsdb", "thirddb"],
            "disk_size" = "20",
        },
        "replicadb" = {
            "db_list" = ["firstdb"],
            "disk_size" = "",
        }
    }
}

main.tf

resource "google_sql_database_instance" "master_sql_instance" {
...
}

resource "google_sql_database" "database" {
  for_each = var.sql_var
  name =  "${element(each.value.db_list, count.index)}"
  instance = "${google_sql_database_instance.master_sql_instance[each.key].name}"

  count =  "${length(each.value.db_list)}"
}

Error Message

Error: Invalid combination of "count" and "for_each"

on ../main.tf line 43, in resource "google_sql_database" "database": 43: for_each = var.sql_var

The "count" and "for_each" meta-arguments are mutually-exclusive, only one should be used to be explicit about the number of resources to be created.

1

1 Answers

0
votes

What the error message tells you is that you cannot use count and for_each together. It looks like you are trying to create 3 main databases and 1 replica database am I correct? What I would do is create your 2 master instances and then transform your map variable to create the databases.

terraform {
  required_version = ">=0.13.3"

  required_providers {
    google = ">=3.36.0"
  }
}

variable "sql_instances" {
  default = {
    "main_instance" = {
      "db_list"   = ["first_db", "second_db", "third_db"],
      "disk_size" = "20",
    },
    "replica_instance" = {
      "db_list"   = ["first_db"],
      "disk_size" = "20",
    }
  }
}

locals {
  databases = flatten([
    for key, value in var.sql_instances : [
      for item in value.db_list : {
        name     = item
        instance = key
      }
    ]
  ])
  sql_databases = {
    for item in local.databases :
    uuid() => item
  }
}

resource "google_sql_database_instance" "sql_instance" {
  for_each = var.sql_instances
  name     = each.key

  settings {
    disk_size = each.value.disk_size
    tier      = "db-f1-micro"
  }
}

resource "google_sql_database" "sql_database" {
  for_each = local.sql_databases
  name     = each.value.name
  instance = each.value.instance

  depends_on = [
    google_sql_database_instance.sql_instance,
  ]
}

Then, first run terraform apply -target=google_sql_database_instance.sql_instance and after this run terraform apply.